Skip to main content

Posts

Showing posts with the label design pattern

Decorator Design Pattern

Intent:
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.

Problem:
Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Solution:
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"); } } …