Sunday, September 28, 2014

Decorator Design Pattern

No comments:
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
{

    public class UpperStream : Stream
    {
        private Stream _stream;
        public UpperStream(Stream stream)
        {
            this._stream = stream;

        }
        public override long Length
        {
            get { return _stream.Length; }
        }
        public override int 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;
        }
        public override bool CanRead
        {
            get { return true; }
        }
        public override bool CanSeek
        {
            get { throw new NotImplementedException(); }
        }
        public override bool CanWrite
        {
            get { throw new NotImplementedException(); }
        }
        public override void Flush()
        {
            throw new NotImplementedException();
        }
        public override long Position
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }
        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hello Decorator";
            MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(message));
            UpperStream stream = new UpperStream(ms);
            StreamReader reader = new StreamReader(stream);
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}
Read More

Strategy Design Pattern

No comments:
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
{

    public interface ISerializer
    {
        void Serialize();
    }
    public class XmlSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Xml serilizer Invoked");
        }
    }
    public class JsonSerializer : ISerializer
    {
        public void Serialize()
        {
            Console.WriteLine("Json serializer Invoked");
        }
    }
    public class Context
    {
        private ISerializer _serializer;
        public Context(ISerializer serializer)
        {
            this._serializer = serializer;
        }
        public void Serialize()
        {
            _serializer.Serialize();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Context ctx = new Context(new XmlSerializer());
            ctx.Serialize();
        }
    }
}
Read More

Friday, September 19, 2014

Adapter Design Pattern

No comments:
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Adapter
{

    public class VendorA
    {

        public string GetResponse()
        {

            return "<Root><Item><Column1>John</Column1> <Column2>Doe</Column2><Column3>John@email.com</Column3> </Item></Root>";
        }
    }

    public class VendorB
    {
        public string GetResponse()
        {

            return "John,Doe,John@email.com\nsantosh,singh,santosh@gmail.com";
        }


    }
    public interface IRquest
    {
        string Get();

    }
    public class Adapter : IRquest
    {
        private VendorB _vendorb = new VendorB();
        public string Get()
        {
            var lines = _vendorb.GetResponse().Split('\n');


            var xml = new XElement("Root",
               lines.Select(line => new XElement("Item",
                  line.Split(new char[] { ',' })
                      .Select((column, index) => new XElement("Column" + index, column)))));

            return xml.ToString();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Adapter client = new Adapter();
            var response = client.Get();
            Console.WriteLine(response);
        }
    }
}

Read More