Working with Simple Factory Pattern

Hello friends,

Today we will go through another creational design pattern called Simple Factory.

Before talking about its implementation let’s begin with some fundamental questions as in the following.

Purpose of the Factory pattern

I can think of two main objectives of using the Factory pattern. One is to achieve loose coupling between the client and business layer, another is to keep all the code for all the object instantiation logic in one place.

Purpose of loose coupling

In modern software development where changes in existing systems are frequent and software design is expected to be scalable, not having a loosely-coupled design can create many problems.

For example, in an application with a 3-layer architecture, if object creation logic is at the client side, for any new addition of concrete classes, the developer needs to modify not just the business but the client layer as well. Think about the maintainability and added testing effort.

How about if the client is only aware of the high-level contracts and not about its concreate implementation?

Yes, you got it right! The client just must pass the type of the object it needs and it will get it using the Factory Pattern.

Enough theory. Now let’s talk about implementation.

How to use the Simple Factory Pattern

Let’s try to understand using a simple example.

Assume the client wants to know the on-road price of various brands of cars and have an interface as in the following.

  • interface ICar
  • {
  •     string GetOnRoadPrice(string model);
  • }

We need to create a Factory class now that will sit between the client and business layers and it will provide the required object to the client based on the car brand passed.

  • class CarFactory
  • {
  •     static public ICar GetCar(string carBrand)
  •     {
  •         if (carBrand == “Maruti”)
  •         {
  •             return new Maruti();
  •         }
  •         else if (carBrand == “Hyundai”)
  •         {
  •             return new Hyundai();
  •         }
  •         return null;
  •     }
  • }

And here goes the concreate business classes.

  • class Maruti: ICar
  • {
  •     public string GetOnRoadPrice(string model)
  •     {
  •         if (model == “Alto 800 VXI”)
  •         {
  •             return “3.4 Lakhs INR”;
  •         }
  •         else
  •         {
  •             return “Information not available!”;
  •         }
  •     }
  • }
  • class Hyundai: ICar
  • {
  •     public string GetOnRoadPrice(string model)
  •     {
  •         if (model == “Grand i10 Magna 1.2 BSV”)
  •         {
  •             return “5.4 Lakhs INR”;
  •         }
  •         else
  •         {
  •             return “Information not available!”;
  •         }
  •     }
  • }

Now let’s see how the client can use the setup we have created so far.

  • //Client side
  • Console.Title = “Factory pattern demo”;
  • ICar car = null;
  • string model = null;
  • //Maruti
  • car = CarFactory.GetCar(“Maruti”);
  • model = “Alto 800 VXI”;
  • Console.WriteLine(“On-road price for {0} car is: {1} “, model, car.GetOnRoadPrice(model));

Output:

  • //Hyundai
  • car = CarFactory.GetCar(“Hyundai”);
  • model = “Grand i10 Magna 1.2 BSV”;
  • Console.WriteLine(“On-road price for {0} car is: {1} “, model, car.GetOnRoadPrice(model));

Output:

And here goes the class diagram.
As you can see in the preceding code, the client is getting the required object by just passing the car brand. And then it calls the GetOnRoadPrice method to get the On-road price by passing model name. So just to summarize, using simple factory, we achieved the following.
  • Loose coupling between client and business layers.
  • Placed object creation logic at common place.
  • Abstracted concreate classes (Maruti, Hyundai) from client.

I hope you have liked this article. I look forward to your comments/suggestions.

Working with Singleton Design Pattern

Hello friends,

I am here to continue the learning series regarding Design Patterns. Today we will go through one of the popular design pattern called Singleton.

In case you have not had a look at our first article, go through the following link:

Before talking about its implementation let’s begin with some fundamental questions as in the following.

Use of the Singleton Pattern

As the name suggests, the Singleton Pattern allows only one instance of a class to be created.

Let’s start by putting some questions to understand the concept.

When do we need to have only one instance of a class?

There are many possible requirements for a instance of a class but they all tend to have the one objective that we don’t want to change the state of the object or we want to keep the class stateless.

A simple example could be that you want to load some master data at once and let the consumers of the data make a call to the Singleton class instead of each consumer making various calls by creating a new instance.

In general, in any complex enterprise application, Repository and Data Access Layer classes can be seen as a Singleton since typically we don’t want them to maintain the state in these layers.

Some other example could be cross-cutting concerns like Logging, Configuration, Caching and so forth that can also be implemented as a Singleton since we want a single and global point of access to these classes.

Apart from the core consideration explained above, I have seen that developers, mostly not so experienced sometimes, create unnecessarily instances that creates not just an overhead to memory but also impacts the overall performance of an application.

Why not Static classes?

There can be several reasons why to not use a static class however I can think of a few as follows.

  • There can be cases where you want to implement interfaces (maybe to implement IOC, I will explain IOC later) in a class that can be done in a Singleton implementation but not in the static one.
  • If required, you can use a singleton class as a method parameter whereas you cannot do that with a static class.

Special care for Singleton classes

We need to take special care for Singleton classes. The idea of a state of a class comes with some extra care that means we need to handle synchronization issues in multi-threaded environments.

Enough theory, now let’s talk about implementation.

Let’s have a look at the most basic implementation.

In the first example below, we have implemented a Singleton with Lazy loading since the instance will not be created until the caller calls the GetInstance method for the first time.

  • public class SingletonClass
  • {
  •     private static SingletonClass instance = null;
  •     private SingletonClass() {}
  •     public static SingletonClass GetInstance
  •     {
  •         get
  •         {
  •             if (instance == null)
  •             {
  •                 instance = new SingletonClass();
  •             }
  •             return instance;
  •         }
  •     }
  • }

Let’s try to fix the sync issue that may arise in multi-threaded environments. For this, we will use a double-lock mechanism.

  • public class SingletonClass
  • {
  •     private static SingletonClass instance = null;
  •     private static object lockMe = new object();
  •     private SingletonClass() {}
  •     public static SingletonClass GetInstance
  •     {
  •         get
  •         {
  •             if (instance == null)
  •             {
  •                 lock(lockMe)
  •                 {
  •                     if (instance == null)
  •                     {
  •                         instance = new SingletonClass();
  •                     }
  •                 }
  •             }
  •             return instance;
  •         }
  •     }
  • }

And in the last, Singleton with static initializations. Please note that the .NET Framework guarantees thread safety for static initialization so we don’t need extra care for sync issues however we may not get the benefit of lazy loading of objects here.

  • public class SingletonClass
  • {
  •     private static SingletonClass instance = new SingletonClass();
  •     private SingletonClass() {}
  •     public static SingletonClass GetInstance
  •     {
  •         get
  •         {
  •             return instance;
  •         }
  •     }
  • }

Conclusion:

In the article, we have gone through what singleton design pattern is, when it should be used and how it should be used.
I hope you will find this article useful. Look forward to your comments/suggestions.

Implicit and Explicit Interface Implementation using C#

Hello guys,

An interface in C# is usually used to create loosely-coupled and contract-based designs. It can contain signatures (declarations) of the Methods, Properties, Indexers and Events. The implementation of the methods/properties and so on is done in the class that implements the interface. An interface can inherit one or more interfaces, in other words it supports multiple inheritance whereas classes don’t.

Implicit interface implementation

This is the most regular or obvious way  to implement members of an interface. Here we don’t specify the interface name of the members and implement implicitly. The method can be declared at any interface (s) the class implements.
For example:
  • interface ITest
  • {
  •     void TestMethod();
  • }
  • class TestClass: ITest
  • {
  •     public void TestMethod()
  •     {
  •         Console.WriteLine(“Implicit Interface Implementation”);
  •     }
  • }
The call of the method is also not different. Just create an object of the class and invoke it.
  • class Program
  • {
  •     static void Main(string[] args)
  •     {
  •         TestClass obj = new TestClass();
  •         obj.TestMethod(); //Way to call implicitely implemented method
  •     }
  • }

Explicit interface implementation

This is another way to implement members of an interface. Here we need to specify the interface name of the members. The following example explains that.

  • class TestClass: ITest
  • {
  •     void ITest.TestMethod()
  •     {
  •         Console.WriteLine(“Explicit Interface Implementation”);
  •     }
  • }
The constraint with explicit implementation is that an explicitly implemented member cannot be accessed using a class instance, but only through an instance of the interface. Please have a look at the example below.
  • class Program
  • {
  •     static void Main(string[] args)
  •     {
  •     ITest obj2 = new TestClass();
  •         obj2.TestMethod();
  •     }
  • }
I hope you have liked the article. Please share your comments.