Design Patterns

When i was at collage and went to programming architecture courses i often went to sleep during some classes because they were mostly theoretical and had no actual code in them, just a overview of forms in witch software could be written

As time went by and i started to actually programming, i found myself inventing solutions to some problems that i had without even knowing that those solutions were already there

Design patterns are solutions to common coding problems, most or if not all design patterns are relay on the world of object oriented design concepts like: polymorphism, inheritors and encapsulation

A design pattern is a solution to a specific problem and it is important to match the pattern to the problem and not the opposite, do not try to modify the problem just to solve it with a specific pattern because it will only make the problem even worst

There some patterns that i regularly use and some that i only used one, here are some of them:

Chain of responsibility

Used when there is a need to chain several processes or handlers to execute all the processes one after another of until one process solves the desired problem.

This pattern is recommended for more then five handlers to be chain together, few handles will just complicate the use.

Good example of COR(Chain of responsibility) if a web server, a web server like IIS, IIS process each page,like HTML or aspx with a specific parsing handler so each page goes to a chain of handlers until he finds the right one.

Recently i used ORC to chain couple of handlers that deal with client management in an online store.

Here, in this example i have two chained, each chain consist of several handlers, the first will make 3 discounts to a client and the second chain will do the same thing but with a name change in the end.

Here are all the classes:

public class Client
    {
        public string Name { get; set; }
        public string ID { get; set; }
        public double Account { get; set; }
    }
    public abstract class IClient
    {
        protected Client _client;
        protected IClient nextProcess;

        public void setClient(Client client)
        {
            _client = client;
        }

        public void setProcess(IClient _process)
        {
            _process._client = _client;
            nextProcess = _process;
        }
        public abstract void runProcess();
    }
    public class Process1 : IClient
    {
        public override void runProcess()
        {

            _client.Account = _client.Account - _client.Account * 0.1;
            Console.WriteLine("Fist discount to client "+_client.Name +" account:"+_client.Account);
            if (nextProcess != null)
            {
                nextProcess.runProcess();
            }
        }
    }
    public class Process2 : IClient
    {
        public override void runProcess()
        {
            _client.Account = _client.Account - _client.Account * 0.2;
            Console.WriteLine("Second discount to client " + _client.Name + " account: " + _client.Account);
            if (nextProcess != null)
            {
                nextProcess.runProcess();
            }
        }
    }
    public class Process3 : IClient
    {
        public override void runProcess()
        {
            _client.Account = _client.Account - _client.Account * 0.3;
            Console.WriteLine("Third discount to client " + _client.Name + " account: " + _client.Account);
            if (nextProcess != null)
            {
                nextProcess.runProcess();
            }
        }
    }
    public class ProcessChangeName : IClient
    {
        public override void runProcess()
        {
            _client.Name = "Avi";
            Console.WriteLine("The client name was changed to " + _client.Name);
            if (nextProcess != null)
            {
                nextProcess.runProcess();
            }
        }
    }

And here is the main method:

static void Main()
        {
            Console.WriteLine("Do only a discount chain");
            //only discount chain
            Process1 process1 = new Process1();
            Process2 process2 = new Process2();
            Process3 process3 = new Process3();
            ProcessChangeName proccess4 = new ProcessChangeName();
            Client client = new Client{Name="Dany",ID="123123",Account=100};
            process1.setClient(client);
            process1.setProcess(process2);
            process2.setProcess(process3);
            process1.runProcess();
            Console.WriteLine("");
            Console.WriteLine("Do a discount chain and a name change at the end:");

            //discount chain and a name change
            client = new Client { Name = "Dany", ID = "123123", Account = 100 };
            process1.setClient(client);
            process1.setProcess(process2);
            process2.setProcess(process3);
            process3.setProcess(proccess4);
            process1.runProcess();
            Console.ReadLine();
        }

The output of the Main class is:

                    Do only a discount chain
                    Fist discount to client Dany account:90
                    Second discount to client Dany account: 72
                    Third discount to client Dany account: 50.4

                    Do a discount chain and a name change at the end:
                    Fist discount to client Dany account:90
                    Second discount to client Dany account: 72
                    Third discount to client Dany account: 50.4
                    The client name was changed to Avi
        

  1. public abstract class IClient
  2.     {
  3.         protected Client _client;
  4.         protected IClient nextProcess;
  5.  
  6.         public void setClient(Client client)
  7.         {
  8.             _client = client;
  9.         }
  10.  
  11.         public void setProcess(IClient _process)
  12.         {
  13.             _process._client = _client;
  14.             nextProcess = _process;
  15.         }
  16.         public abstract void runProcess();
  17.     }

this abstract class is what makes it all work, inside we have the client class, which consists of the client detail, a reference to the next handler(next process).

The setProccess function sets the reference to the next handler to be invoked and the abstract function runProcess will be implemented by the handler and will have the actual code to execute

public class Process1 : IClient
    {
        public override void runProcess()
        {

            _client.Account = _client.Account - _client.Account * 0.1;
            Console.WriteLine("Fist discount to client "+_client.Name +" account:"+_client.Account);
            if (nextProcess != null)
            {
                nextProcess.runProcess();
            }
        }
    }

This handler's job is to make a discount to the client and he is implementing the IClient class.

The runProccess makes the discount and then, it runs the next handler that was set by the setProcess function

Inversion of control

On of the thing that i try to keep while i code is to ensure that each code does only what it needs to to, advisably one or two functions, and delegate other functionalities to other code or classes, this is also called the single responsibility idea.

One pattern that deals with this idea is IOC-inversion of control, IOC in the world of OOF says that incase you have a code inside a class that is not relevant to the main idea of the class, that code should be moved to another class.

Here is an example of why IOC is needed:

public class DiscountPlan
        {
            public void getDiscount()
            {

            }
        }
        public class OrdinaryPlan
        {
            public void getDiscount()
            {

            }
        }

        public class Store
        {
            public Store()
            {
                Console.WriteLine("For ordinary plan press 1, for discount plan press 2");
                string paymentPlan = Console.ReadKey().Key.ToString();
                if (paymentPlan == "1")
                {
                    OrdinaryPlan Or = new OrdinaryPlan();
                    Or.getDiscount();
                }
                if (paymentPlan == "2")
                {
                    DiscountPlan dp = new DiscountPlan();
                    dp.getDiscount();
                }
            }
        }

        static void Main(string[] args)
        {

            Store store = new Store();

In the example above we try to decide which payment order to use, this code is problematic for couple of resonse:

  1. The store class main role is to manage the store, but here she is being used to also interact with the user and decide which plan to use
  2. There is a tight coupling between the number of plans that we have and the number of objects we need to create in the store class, so every change to a store(addition, deletion) requires changes in the store class
  3. In this class we create object and use the same functions twice or more
  4. All the plans are using the functions with the same name, why not use interfaces?

To fix those issues we will and to make every class deal with it's own responsibility.

This is how i solve this problem:

public interface IPlan
        {
            void getDiscount();
        }

        public class DiscountPlan : IPlan
        {
            public void getDiscount()
            {
                Console.WriteLine("Discount plan has been activated");
            }
        }
        public class OrdinaryPlan : IPlan
        {
            public void getDiscount()
            {
                Console.WriteLine("Ordinary plan has been activated");
            }
        }

        public class Store
        {
            IPlan _plan;
            public Store(IPlan plan)
            {
                _plan = plan;
                _plan.getDiscount();
            }
        }

        static void Main(string[] args)
        {
                Console.WriteLine("For ordinary plan press 1, for discount plan press 2");
                string paymentPlan = Console.ReadKey().KeyChar.ToString();
                Store store;
                if (paymentPlan == "1")
                {
                    store = new Store(new OrdinaryPlan());
                }
                if (paymentPlan == "2")
                {
                    store = new Store(new DiscountPlan());
                }
        }

The changes that to the code above are:

  1. Now the main class asks the user which plan to choose and then sends the chosen class to the store class by a constructor. By this we fallow the single responsibility principle, every class now deals with only their own responsibility
  2. To enable sending multiple plans to the store class we use polymorphism: every plan class is now inheriting form the IPlan interface.
  3. By inheriting form the IPlan interface, the store class can now execute the getDiscount function regardless on what type of plan we sand as long is it inherits form the IPlan interface.

So in conclusion every class now deals with own responsibility by moving the dialog with the user to another class

Dependency injection

In the last pattern, inversion of control, we have moved the responsibly of deciding what discount plan to use from the store class to the supposed UI class, which is the main method.

We did reassign the responsibility to the other class and improved the design with polymorphism but unfortunately we didn't achieve one important principle in programming that is - loosely coupling.

The problem in the previous solution is that it was a tightly coupled solution, tight coupling means: when ever we change some thing in one place in the code we have to do the changes in other places too, changes could happen but they should me as minimum as possible.

For example, if we will add a new Ordinary plan and want to use the new plan called - NewOrdinaryPlan, we would have to change the Ordinary plan to the new one in all the places in the code, that is not a huge deal when we only have to preformed one change but what if we have multiple uses of the ordinary plan in many places of our program? Then we would have to do lots of renaming in the code.

What if there is a way to make only one change that will effect the entire code?

This way exists and it is called dependency injection (DI), with DI we could achieve decoupling.

public interface IPlan
        {
            void getDiscount();
        }
        public class DiscountPlan : IPlan
        {
            public void getDiscount()
            {
                Console.WriteLine("Discount plan has been activated");
            }
        }
        public class OrdinaryPlan : IPlan
        {
            public void getDiscount()
            {
                Console.WriteLine("Ordinary plan has been activated");
            }
        }
        public class Store
        {
            IPlan _plan;
            public Store(IPlan plan)
            {
                _plan = plan;
                _plan.getDiscount();
            }
        }
        static void Main(string[] args)
        {
            IUnityContainer objContainer = new UnityContainer();
            objContainer.RegisterType<IPlan, OrdinaryPlan>("ordinaryPlan");
            objContainer.RegisterType<IPlan, DiscountPlan>("discountPlan");
            objContainer.RegisterType<Store>("storeWithOrdinaryPlan",
                new InjectionConstructor(
                    new ResolvedParameter<IPlan>("ordinaryPlan")));
            objContainer.RegisterType<Store>("storeWithDiscountPlan",
                new InjectionConstructor(
                    new ResolvedParameter<IPlan>("discountPlan")));
            Console.WriteLine("For ordinary plan press 1, for discount plan press 2");
            string paymentPlan = Console.ReadKey().KeyChar.ToString();
            Store store;
            if (paymentPlan == "1")
            {
                store = objContainer.Resolve<Store>("storeWithOrdinaryPlan");
            }
            if (paymentPlan == "2")
            {
                store = objContainer.Resolve<Store>("storeWithDiscountPlan");
            }

In the code above we see a solution to the problem, this solution does not remove all the need for changes but it minimizes them significantly.

All the changes from the previous solution are in the main function, what we did here is we used a DI framework called Unity application block, to do dependency injection, it is easy to add to visual studio, just search "unity" in Nuget and choose the result named Unity and install it.

IUnityContainer objContainer = new UnityContainer();
            objContainer.RegisterType<IPlan, OrdinaryPlan>("ordinaryPlan");
            objContainer.RegisterType<IPlan, DiscountPlan>("discountPlan");
            objContainer.RegisterType<Store>("storeWithOrdinaryPlan",
                new InjectionConstructor(
                    new ResolvedParameter<IPlan>("ordinaryPlan")));
            objContainer.RegisterType<Store>("storeWithDiscountPlan",
                new InjectionConstructor(
                    new ResolvedParameter<IPlan>("discountPlan")));

In the first line we create a unity block container, then, because unity application block is not part of the .NET framework,we need to register our classes to this container.

When you register an objects you must also specify his interface (if he has one) and specify the object himself.

We also specify the names so we can take the objects with the injection we want from the container by name as we did with the resolve function.

Notice how we register the two customer objects and each one has a different plan injection, one an ordinary and the other a discount

This code code can be written any where in the application: in the start up code, like global.aspx, app.xaml.cs or even in an xml configure file

By registering objects, the unity application block recognizes the the interfaces and injects the depended objects into them, like we injected the ordinary plan object in to the IPlan interface, in the store object.

So now in this example we have a decupled architecture, our UI layer is no longer depended on the logic layer that has our other classes.

By using DI we inject object that are depended to a class and by that achieving a loosely coupled architecture, a good examples of a decoupled architecture are MVVM, that used in WPF and MVC, that is used in Asp.NET.

When building big projects using a decoupled architecture is very helpful.