Post

10 Design Patterns that every developer should know

10 Design Patterns that every developer should know

How to write reusable and extensible object-oriented software - (Part One)

design patterns

What are design patterns?

Programs need to be flexible, reusable and maintainable, they need to be elegant. Design patterns are elegant solutions to repeating problems in software design. They describe a problem, a solution to the problem, where to apply the solution and it’s consequences. When a developer masters the design patterns he/she can reuse already established designs and avoids common mistakes from the painful experience of others. Mastering design patterns will also equip you with the understanding of common vocabulary and help you communicate with other developers at a more abstract level during analysis and development of software. Design patterns are programming language independent strategies, the patterns represent an idea and not a particular implementation.

Example

You are required to create a class from which only a single object should be created which can be used by other classes.

Solution

The Singleton Design Pattern is the best solution to this problem. We are going to review the pattern later in this article.

History

In 1994, four authors, popularly known as the Gang of Four(GoF) published a book known as Design Patterns - Elements of Reusable software which gave birth to the concept of Design patterns in Software development. The GoF came up with 23 design patterns which can be categorized into 3: Creational, Structural and Behavioural Patterns.

i) Creational Patterns

Creational patterns focuses on the creation of objects i.e how to create objects in a manner that is suitable to the situation. Creation pattern is further divided into five categories:

a) Singleton Pattern

This pattern involves a single class which is responsible for creating an object while making sure only one object gets created. The pattern restricts the instantiation of a class to only one instance. You can use the instance when you need in different parts of your application.

Real life Example

A country can have only one official government regardless of the identities that forms the government.

Computer World Example

In the development of software logging frameworks use the Singleton Pattern a lot. You can also create a single configuration file or database connection string which will be used anywhere in the application when required.Let’s look at a program example where we create an application configuration settings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//configuration class
    public class ConfigurationManager
    {
        //Store our settings in dictionary - key value pair
        Dictionary<string, string> configs = new Dictionary<string, string>();

        //we need two methods for setting and getting our app settings
        public void setConfigSettings(string key, string value)
        {
            configs.Add(key, value);
        }

        public string getConfigSettings(string key)
        {
            return configs[key];
        }

    }

Let’s create a new setting in the main method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   class Program
    {

        static void Main(string[] args)
        {
            //Create a new instance of ConfigurationManager
            ConfigurationManager configManager = new ConfigurationManager();
            //Create a new setting
            configManager.setConfigSettings("setting1", "value1");

            //Read the vlaue of setting1 using the configManager instance
            Console.WriteLine(configManager.getConfigSettings("setting1"));

            //Create another instance of ConfigurationManager
            ConfigurationManager configManager2 = new ConfigurationManager();

            //Read the value of setting2 using the configManager2 instance
            Console.WriteLine(configManager2.getConfigSettings("setting1"));

            Console.ReadKey();
        }
    }

In the example above, We have created a new instance of ConfigurationManager and created a new setting. The setting can be accessed anywhere in the application using the configManager instance. When we create another ConfigurationManager instance and try to access setting1, we get a exception saying:

The given key ‘setting1’ was not present in the dictionary.

This can be avoided by simply having only one instance of the ConfigurationManager class which will accessed anywhere in the application when needed. The singleton pattern observes the following rules:

  1. A single private field that holds the instance of the class, it ensures a global point of access. Under the hood, this method calls the private constructor to create an object and saves it in a static field. The sealed keyword ensures that a subclass cannot misuse it.
  2. A private Constructor - You cannot create a new instance of the class outside the class.
  3. Define an operation(method) to return the single instance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Configuration class
    public sealed class ConfigurationManager
    {
        //1. single private field that holds the instance of the class 
        private static readonly ConfigurationManager instance = new ConfigurationManager();

        //2. make the constructor private
        private ConfigurationManager() { }

        //3. define an operation to return the single instance
        public static ConfigurationManager Instance
        {
            get
            {
                return instance;
            }

        }

        //Store our settings in dictionary
        Dictionary<string, string> configs = new Dictionary<string, string>();

        //we need two methods for setting and getting our app settings
        public void setConfigSettings(string key, string value)
        {
            configs.Add(key, value);
        }

        public string getConfigSettings(string key)
        {
            return configs[key];
            
        }
    }

The Main Method:

1
2
3
4
5
6
7
8
9
10
11
12
13
 static void Main(string[] args)
        {
            //get the instance of ConfigurationManager
            ConfigurationManager configManager = ConfigurationManager.Instance;
            //Create a new setting
            configManager.setConfigSettings("setting1", "value1");

            //Read the value of setting1 using the configManager instance
            Console.WriteLine(configManager.getConfigSettings("setting1"));

            Console.ReadKey();
        }

Pros
  1. Ensures that a class has only one instance.
  2. The singleton object is initialized only when it’s requested for the first time.
Cons
  1. Violation of SRP - The pattern violates the Single Responsibily Principle - they control their own creation and lifecycle.
  2. The pattern requires a special treatment in a multithreaded environment. This prevents multiple threads from creating a singleton object multiple times.
  3. Increases tight coupling - Changes to one component in your application is difficult as it would affect all other components that are connected to it.
  4. Unit Testing becomes difficult - Increased coupling makes creating mocks during unit testing difficult. The Singleton Pattern uses Static Method which makes unit testing difficult since you cannot mock or stub.
Will I ever use this pattern?

Absolutely. Singletons are objects of which there can only ever be exactly one instance. The singleton pattern is easy to understand and implement, which makes it a favorite tool of people afflicted with golden hammer syndrome(When the only tool you have is a hammer, everything looks like a nail). it’s common to find Singletons in use where global variables should be used instead.

b) Factory Pattern

According to the gang of four “A Factory is an object that is used for the creation of other objects”. This simply means that a factory is a class with a method which creates and returns different types of objects based on the input parameter. This is used when we have to return the object of one child class when we have a Parent Class and n number of Child Classes. The Factory Pattern let a class differ instatiation to a child class. The pattern creates an object without exposing the object creation logic to the client.

Real World Example

A factory is a place where products are created. Based on the order, a car factory can create different models of a car based on requirement. The same case applies in the Factory Pattern. A factory(a class), will create products(objects) based on incoming parameters.

Example

Let’s understand the Factory Design Pattern using an example. We are going to develop a program that will show credit card details based by the user input.

The following diagram shows three credit cards: Gold Visa, Platinum Visa and MoneyBack MasterCard. The credit cards can be child classes to a CreditCard super class or a super interface. The CreditCard super class can have 3 methods: GetCardType, GetCreditCardLimit and GetCreditCardAnnualCharge. Our program requirement is to ask the user to select a credit card, we will use that input to display the details the card.

Code Implementation without using the Factory Design Pattern
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace FactoryDesignPattern
{
    //CreditCard Interface
    public interface CreditCard
    {
        string GetCardType();
        decimal GetCreditCardLimit();
        decimal GetCreditCardAnnualCharge();
    }
    //Gold Visa Class
    class GoldVisa : CreditCard
    {
        public string GetCardType()
        {
            return "Gold Visa";
        }

        public decimal GetCreditCardAnnualCharge()
        {
            return 400;
        }

        public decimal GetCreditCardLimit()
        {
            return 400000;
        }
    }
    //Platimun Visa Class
    class PlatinumVisa : CreditCard
    {
        public string GetCardType()
        {
            return "Platimun Visa";
        }

        public decimal GetCreditCardAnnualCharge()
        {
            return 500;
        }

        public decimal GetCreditCardLimit()
        {
            return 500000;
        }
    }

    //MoneyBackMasterCard Class
    class MoneyBackMasterCard : CreditCard
    {
        public string GetCardType()
        {
            return "MoneyBack Mastercard";
        }

        public decimal GetCreditCardAnnualCharge()
        {
            return 600;
        }

        public decimal GetCreditCardLimit()
        {
            return 600000;
        }
    }
}

The client code

In the client code(Program.cs) we will ask the user to select a credit card. We will then create an instance of the selected credit card and print out it’s details in the console.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 class Program
    {

        static void Main(string[] args)
        {

            Console.WriteLine("Select a credit card");
            Console.WriteLine("1.Gold Visa  2. Platinum Visa 3.MoneyBack Mastercard");
            var selectedCreditCard = Convert.ToInt32(Console.ReadLine());

            //Based of the CreditCard Type we are creating the
            //appropriate type instance using if else condition
            CreditCard cardDetails = null;
            if (selectedCreditCard == 1)
            {
                cardDetails = new GoldVisa();
            }
            else if (selectedCreditCard == 2)
            {
                cardDetails = new PlatinumVisa();
            }
            else if (selectedCreditCard == 3)
            {
                cardDetails = new MoneyBackMasterCard();
            }

            if (cardDetails != null)
            {
                Console.WriteLine("selectedCreditCard : " + cardDetails.GetCardType());
                Console.WriteLine("CreditLimit : " + cardDetails.GetCreditCardLimit());
                Console.WriteLine("AnnualCharge :" + cardDetails.GetCreditCardAnnualCharge());
            }

            else
            {
                Console.Write("Invalid Card Type");
            }

            Console.ReadLine();
        }

    }

When we run our program and select a credit card, an object is created and the details of the card are displayed in the console. For case 1, the output is as follows:

1
2
3
selectedCreditCard : Gold Visa
CreditLimit : 400000
AnnualCharge :400
What’s the problem with this implementation?

The code implementation above introduces the following problems:

  1. Tight coupling between the Client class(Program.cs) and the Product class(Gold, Platinum and Money Back).
  2. We will need to modify the Main method in the client class when we create another credit card which violates the open closed principle Open Closed Princle.
Program implemetation using the Factory Design Pattern.

We described the Factory Pattern as a pattern that creates an object without exposing the object creation logic to the client. We can modify the previous implementations as follows to add more flexibility to our program.

  1. Create a CreditCardFactory class(A factory creates products i.e credit card objects)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
   public class CreditCardFactory
    {
        public static CreditCard CreateCreditCard(int Creditcard)
        {
            CreditCard cardDetails = null;
            switch (Creditcard)
            {
                case 1:
                    cardDetails = new GoldVisa();
                    break;
                case 2:
                    cardDetails = new PlatinumVisa();
                    break;
                case 3:
                    cardDetails = new MoneyBackMasterCard();
                    break;
                default:
                    throw new ApplicationException("Unknown Credit Card Cannot be created");
            }
            return cardDetails;
        
        }
    }
  1. Modify the Client Class as follows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 class Program
    {

        static void Main(string[] args)
        {

            Console.WriteLine("Select a credit card");
            Console.WriteLine("1.Gold Visa  2. Platinum Visa 3.MoneyBack Mastercard");
            var selectedCreditCard = Convert.ToInt32(Console.ReadLine());

            //Based of the CreditCard Type we are creating the
            //appropriate type the Credit Card Factory Class

            CreditCard cardDetails = CreditCardFactory.CreateCreditCard(selectedCreditCard);
          
            if (cardDetails != null)
            {
                Console.WriteLine("selectedCreditCard : " + cardDetails.GetCardType());
                Console.WriteLine("CreditLimit : " + cardDetails.GetCreditCardLimit());
                Console.WriteLine("AnnualCharge :" + cardDetails.GetCreditCardAnnualCharge());
            }

            else
            {
                Console.Write("Invalid Card Type");
            }

            Console.ReadLine();
        }

    }

The output when we select 1:

1
2
3
selectedCreditCard : Gold Visa
CreditLimit : 400000
AnnualCharge : 400
When to use the Factory Design Pattern

Use the Factory design pattern when you don’t know all the types before hand and the product implementation is going to change over time. The Factory Method separates product construction code from the code that actually uses the product(Client). Therefore it’s easier to extend the product construction code independently from the rest of the code.

Pros
  • You avoid tight coupling between the Client and the Concrete Products.
  • Supports Single Responsibilty Priniciple
  • Supports the Open/Closed Principle. You can introduce new products without breaking the existing code.
Cons

The pattern increases code complexity as one need to introduce a lot of new subclasses.

Will I ever use this pattern?

Absolutely. Any time you need to create groups of related objects, Factory Method is one of the cleanest ways to do so.

C) Builder Design Pattern

Builder is a creational design pattern that enables you to construct complex objects step by step by separating the construction of a complex object from it’s representation. By doing so, a class(the same construction process) can create different representations. The builder pattern is useful when creating objects that have multiple parts. The creation process should be independent of the different parts i.e it should not care how the parts are assembled. This enables us to use the same process to create other representations.

Real World Example

A laptop is an example of a complex object. In order to build a laptop, we have to use small objects such as display, Hard Drive, RAM, Battery, USB ports etc. SO we have to assemble these small objects to build a laptop which is complex object. Depending on a customer request, different objects(hardware parts) can be assembled. A customer can opt for 1TB hard drive with a core i7 processor and another can opt for a 500GB hard drive with a AMD Processor.

Example

Let’s understand the Builder pattern using another example.Suppose we want to develop an application for displaying reports. The reports need to display either in Excel or PDF format depending on the user preference. The two formats are what we call the representations. The structure below illustrates the high level of our requirements.