Design Patterns: Arguments for and against!1 min read

DesignPatternsHeader

Design Pattern┬áis in a way analogous to a pattern which is followed to make a sweater. Yes, to better understand design patterns, we’ll closely look at the steps followed in weaving a sweater. First, there are the input elements i.e. wool, knitting needles; then there is a pattern that is followed thoroughly. Same happens in DP, meaning as input we have classes/Interfaces, object and as a strategy, we have a certain pattern that is to be strictly followed.

In the article below we’ll go through all the positive and negative aspects of most commonly used design patterns.

Singleton Design Pattern: As per GOF(Gangs of four), This pattern ensures a child has only one instance and provides a global point of access to it.
Advantages :

  1. Lazy Instantiation: Object in singleton can be created only when in need, for e.g. as quoted below, the static method can be called upon whenever required.

    public static MyClass getInstance() {
    return new MyClass();
    }

  2. Static Initialization: As mentioned in above example, objects can be initialized inside a static method and can be referred or called by just mentioning the
    MyClass myClassObj = MyClass.getInstance();
  3. Instance control: Singleton prevents other objects from instantiating their own copies of the Singleton object, ensuring that all objects access the single instance.

Disadvantages:

  1. Be careful, when using multiple class loaders, as this could defeat the implementation & can result in multiple instances.
  2. Singleton pattern can be challenged when used in a multi-threaded environment, and code changes may be required to cope up with the same.
  3. Memory Leak: Singleton can cause a memory leak as they are never disposed of during application running.
  4. Tighter coupling: Singleton has tighter coupling as it only couples with the exact type of the singleton object.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.