Creational Design Patterns

Beyza Celep
8 min readJun 12, 2020

--

Hello,

In my first post I have explained Design Patterns. Today, I am going to continue with Creational Patterns.

Creational Design patterns are using for controlling object creation process or instantiation of a class. We can easily say that Creational Design Patterns are all about the rules and the standards that we want for our class’ and objects’ creation process. We need them because constructors may not be efficient enough all the time : they may be too flexible or too strict for our scenario or they may be expensive to use.

The point of creational patterns can be realized in the caller of the object. Keywords for creational design patterns are : Delegation and Inheritance. If you are not familiar with these terms I can recommend you some sources to have grasp of them.

Let me clarify with an example : In these Corona virus days we are working remotely. There is a database, and we (and also think about team mates who follows same purpose and write code) have to connect to db and to do some basic operations like reaching / updating / deleting the datas. Indeed, what we are doing is to have “object instances” that helps us to connect db and do the necessary operations. But, at the end of the day there is only one database that we all worked on.

These examples can be enlarged. Shortly, we use creational patterns for controlling and managing object creation, inheritance or delegation.

Now, after talking about Creational Patterns, I am going to explain each of them with some basic & conceptional C# code implementations.

Singleton Pattern :

If we want a class to have only one instance and provide a global access point to it, then we use singleton pattern. We’d prefer to use Singleton Pattern if :

  • The situation may cause problem to have multiple instances of a class
  • We want to simplify very complex classes because it is unnecessary to implement them in a way that allows multiple instances (when it is expensive to create that object like db connections).

But in general, it is mentioned as a bad practice that should be avoided by many developers due to it prevents extensibility and also decreases testability of the code by it globalizing a state into the app.

While studying singleton patterns I wondered what is the difference between singleton and static class and here is the answer : Firstly, a singleton can implement interfaces but a static class can’t. Also, singleton is about controlling creation process of instance not only creating instance.

“A singleton allows access to a single created instance — that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.

A static class allows only static methods.” — Jon Skeet

You can see a basic Address Book example below :

class Singleton{private Singleton(){}private static Singleton AddressBook;public static Singleton GetAddressBook(){if (AddressBook == null)AddressBook = new Singleton();return AddressBook;}}

To prevent object creation with “new” keyword, I marked constructor as empty. Then in Program.cs, we can access our object (and can not create it with new keyword) :

Singleton addressBook = Singleton.GetAddressBook();

Factory & Abstract Factory Pattern :

Factory pattern creates just one instance of a couple of derivated classes.

Main logic of factory pattern is : define an interface to create an object, but let sub-classes decide which class to instantiate. This pattern standardizes the object creating process with letting other domain users create their own objects. Shortly, when we use factory pattern, we create the object and let the client create the object types by using the same common interface. So that, the client is totally independent from the object’s creation process : doesn’t need to know about how the object is going to create because it is duty of library anymore.This pattern is mostly used when there are classes that has a lots of common property (derived from the same factory).

Abstract factory is very similar with Factory pattern, we can say that abstract pattern is used in similar scenarios but with more complexity. Abstract pattern says : create different factories for similar product families and add one more level between client and object creating process. So, different from factory pattern we create 2 or more factory as base classes to produce common interfaces.

Now let’s code an example that includes both : Factory and Abstract Factory Pattern :

First we are creating our 2 interfaces for 2 main product types : Car and Motorbike.

public interface ICar{void ManufactureCar();}public interface IMotorbike{void ManufactureMotorbike();}

Now, we are creating our classes that implement our interfaces, with Manufacture() method : Our cars can be Mercedes, BMW or Volkswagen (which are my favorite brands :))and our Motorbikes can be : Harley Davidson, Yamaha or Ducati.

public class Mercedes : ICar{public void ManufactureCar(){Console.WriteLine("Mercedes manufactured");}}public class BMW: ICar{public void ManufactureCar(){Console.WriteLine("BMW manufactured");}}public class Volkswagen: ICar{public void ManufactureCar(){Console.WriteLine("Volkswagen manufactured");}}public class HarleyDavidson : IMotorbike{public void ManufactureMotorbike(){Console.WriteLine("Harley Davidson manufactured");}}public class Yamaha: IMotorbike{public void ManufactureMotorbike(){Console.WriteLine("Yamaha manufactured");}}public class Ducati: IMotorbike{public void ManufactureMotorbike(){Console.WriteLine("Ducati manufactured");}}

Here we are, now creating our Abstract Factory that is necessary for our Car and Motorbike objects’ creation :

public abstract class AbstractFactory{public abstract ICar getCar(string car);public abstract IMotorbike getMotorbike(string motorbike);}

As you can guess, now we should create CarFactory and MotorbikeFactory classes which inherits AbstractFactory :

public class CarFactory : AbstractFactory{public override ICar getCar(string car){if (car == null)return null;if (car.Equals("Volkswagen"))return new Volkswagen();else if (car.Equals("Mercedes"))return new Mercedes();else if (car.Equals("BMW"))return new Bmw();return null;}public override IMotorbike getMotorbike(string motorbike){return null;}}public class MotorbikeFactory :AbstractFactory{public override IMotorbike getMotorbike(string motorbike){if (motorbike == null)return null;if (motorbike.Equals("Harley Davidson"))return new HarleyDavidson();else if (motorbike.Equals("Ducati"))return new Ducati();else if (motorbike.Equals("Yamaha"))return new Yamaha();return null;}public override ICar getCar(string car){return null;}}

Since we have all factories, now we should have a FactoryCreator :

public class FactoryCreator{public static AbstractFactory GetFactory(string type){if (type.Equals("Car"))return new CarFactory();else if (type.Equals("Motorbike"))return new MotorbikeFactory();return null;}}

And finally in Program.cs File :

class Program{static void Main(string[] args){AbstractFactory carFactory = FactoryCreator.GetFactory("Car");AbstractFactory motorbikeFactory = FactoryCreator.GetFactory("Motorbike");ICar car = carFactory.getCar("Volkswagen");IMotorbike motorbike = motorbikeFactory.getMotorbike("Ducati");}
}

As you can see, we just collected the common properties of the objects, then created our interfaces due to them, finally created our factories. This is the main idea / usage of Factory Patterns.

Builder Design Pattern :

  • If creation process of an object is so complex,
  • If constructor takes lots of parameters that are unnecessary to us,
  • If we want to use different combinations of these parameters,

we can apply builder pattern. In builder pattern, objects are creating with builder objects instead of using constructors. As you see, builder is quite similar with abstract factory. Here is the difference : Abstract factory is about what products are made of while builder is about how a single object is making up by different factories or processes. You can see a basic example that is about manufacturing cars that are in different categories (packages) due to customer’s demand.

First, I am creating a Builder Interface :

 public interface IBuilder{void BuildTrendlinePackage();void BuildComfortinePackage();void BuildHighlinePackage();}

Then creating a Director Class which implements my IBuilder Interface :

 class Director{private IBuilder _builder;public IBuilder Builder{set { _builder = value; }}public void buildCheapestProduct(){this._builder.BuildTrendlinePackage();}public void buildFullFeaturedProduct(){this._builder.BuildHighlinePackage();}}

Now, I am crating my Builder class which will literally build my objects :

public class Builder : IBuilder{private Product _product = new Product();public void Reset(){this._product = new Product();}public void BuildTrendlinePackage(){this._product.Add("TrendlinePackage");}public void BuildComfortinePackage(){this._product.Add("ComfortlinePackage");}public void BuildHighlinePackage(){this._product.Add("HighlinePackage");}public Product GetProduct(){Product result = this._product;return result;}}

And finally in Program.cs :

class Program{static void Main(string[] args){//Buildervar director = new Director();var builder = new Builder();director.Builder = builder;Console.WriteLine("Standard basic product:");director.buildCheapestProduct();Console.WriteLine(builder.GetProduct().ListParts());Console.WriteLine("Standard full featured product:");director.buildFullFeaturedProduct();Console.WriteLine(builder.GetProduct().ListParts());// Remember, the Builder pattern can be used without a Director// class.Console.WriteLine("Custom product:");builder.BuildTrendlinePackage();builder.BuildHighlinePackage();Console.Write(builder.GetProduct().ListParts());}}

Prototype Design Pattern :

This patterns looks for efficient ways to create an object. There may be complex objects that costs much when creating (like performance,memory usage etc.). This pattern clones the object to produce them more efficiently in case of need : which means we don’t have to create object every time we need and we do not cost all expensive parameters like performance, memory or time etc. Actually, as it name indicates, this pattern creates a prototype for the objects and use it to produce the object when client demands, instead of creating the object all over again. If we think we will need that object later , builder pattern creates a prototype for it and so we don’t go to the trouble.

Photo by Doug Maloney on Unsplash

You can see my example below. Especially the ones who know about FM will love this example :)

abstract class FootballerPrototype{public abstract FootballerPrototype Clone();}class Footballer : FootballerPrototype{public int FootballerID { get; set; }public string Name { get; set; }public string Surname { get; set; }public int Age { get; set; }public double Height { get; set; }public double Weight { get; set; }public string Club { get; set; }public string League { get; set; }public string Position { get; set; }public int Corners { get; set; }public int Dribbling { get; set; }public int Acceleration { get; set; }public int Balance { get; set; }public override FootballerPrototype Clone (){return this.MemberwiseClone() as FootballerPrototype;}public Footballer(int FootballerID, string Name, string Surname,int Age, double Height, double Weight, string Club, string League,string Position, int Corners, int Dribbling, int Acceleration, int Balance){this.FootballerID = FootballerID;this.Name = Name;this.Surname = Surname;this.Age = Age;this.Height = Height;this.Weight = Weight;this.Club = Club;this.League = League;this.Position = Position;this.Corners = Corners;this.Dribbling = Dribbling;this.Acceleration = Acceleration;this.Balance = Balance;}}

And in Program.cs file :

class Program{static void Main(string[] args){Footballer gomez = new Footballer(1, "Mario", "Gomez", 33, 189, 88, "VfB Stuttgart", "2.Bundesliga", "Striker", 6, 13, 9, 12);Footballer cenk = (Footballer)gomez.Clone();if (gomez.Acceleration.Equals(cenk.Acceleration)){Console.WriteLine("Players have same acceleration");}else{Console.WriteLine("Players don't have same acceleration");}Console.Read();
}
}

I really hope my examples didn’t bored you but helped you to understand at least concepts of creational patterns. Football and cars are two of my biggest passions so I wanted to use them in my examples. Also studying with these kind of examples makes me understand more about design patterns and helps me to remind / apply them while I am working on real issues :)

Hope you enjoyed my post. Waiting to hear your feedback and suggestions.

--

--