Decorator Design Pattern Intro

0

Category : , ,

Decorator Design pattern allows developer to satisfy some SOLID rules:

  • 1) Single Responsibility Principle – Class/Function should do only one task or Class/Function should have only one reason to change.
  • 2) Open Close Principle – Class/Function is open for extension but close for modification.
  • 3) Liskov Substitution type – If type S is derived from Type T then object of Type T can be replaced by object of Type S.


Simple Example of Design Pattern

namespace BasicDecoratorPattern
{
    public class Client
    {
        public Client()
        {
            IBaseService realTimeService = new BasicServiceImplementaion();

            IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
            IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);

            basicRealTimeServiceDecorator1.Print();
            basicRealTimeServiceDecorator2.Print();
        }
    }

    public interface IBaseService
    {
        void Print();
    }

    public class BasicServiceImplementaion : IBaseService
    {
        public void Print()
        {
            Console.WriteLine("Basic Item");
        }
    }

    public class Decorator1OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator1OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator ONE");
        }
    }

    public class Decorator2OnBasic : IBaseService
    {
        private readonly IBaseService BasicRealTimeService;
        public Decorator2OnBasic(IBaseService service)
        {
            BasicRealTimeService = service;
        }

        public void Print()
        {
            BasicRealTimeService.Print();
            Console.WriteLine("Extra functionality from Decorator SECOND");
        }
    }
}




my thanks to: http://www.codeproject.com/Articles/872818/How-and-Where-Decorator-Design-Pattern