Skip to main content


Showing posts from September, 2014

Decorator Design Pattern

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality (also known as Wrapper)

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPattern { publicclass UpperStream : Stream { private Stream _stream; public UpperStream(Stream stream) { this._stream = stream; } publicoverridelong Length { get { return _stream.Length; } } publicoverrideint Read(byte[] buffer, int offset, int count) { var numberOfBytesRead = _stream.Read(buffer, offset, count); for (int i = 0; i < numberOfBytesRead; i++) { buffer[i] = (byte)char.ToUpper((char)((int)buffer[i])); } return numberOfBytesRead; } publicoverrideboo…

Strategy Design Pattern

Strategy Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Encapsulate the different serialization algorithms using the Strategy pattern!
C# Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StrategyPattern { publicinterface ISerializer { void Serialize(); } publicclass XmlSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Xml serilizer Invoked"); } } publicclass JsonSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Json serializer Invoked"); } } …

Adapter Design Pattern

Adapter Pattern: The Adapter pattern converts the interface of a class into another interface that clients expect.The client makes a request on the adapter by invoking a method from the target interface on it and then adapter translates that request into one or more calls on the adaptee using the adaptee interface. The client receives the results of the call and never knows there is an adapter doing the translation

Pre-Condition: You are maintaining an existing system that makes use of a third-party class library from vendor A
Stimulus: Vendor A goes belly up and corporate policy does not allow you to make use of an unsupported class library.
Response: Vendor B provides a similar class library but its interface is completely different from the interface provided by vendor A
Assumptions: You don’t want to change your code, and you can’t change vendor B’s code
Solution?: Write new code that adapts vendor B’s interface to the interface expected by your original code

C# Example

using System;