Design Patterns Introduction and Singleton Pattern implementation in Java

What is Design pattern?

    It gives you a structured approach to solve a common problem in software development. Basically, it gives you a reusable code which is easy to maintain. It is flexible too.

Let us categorize the design patterns.

  • Creational patterns
  • Structural patterns
  • Behavioral patterns

Each of the pattern has its own features given as follows

Creational Patterns:

              As the name suggests, it deals with object creation. For example, Singleton, Builder and Factory design patterns.

Structural Patterns:

              These design patterns deal with classes.The main purpose is to structure the class and relationships are made.

Eg: Adapter, Decorator and Proxy.

Behavioral Patterns:

              This design pattern is made for communication between objects.

Eg: Command, Observer and Strategy.

Let us create Singleton Design Pattern.

Java implementation of Singleton Pattern:

              This design pattern has only one instance across the entire application. Even the user creates more than one instance.

  • Singleton class is created with one instance in1.
  • ‘getInstance() method checks the instance is created or not. If it is not created, it creates the instance here.
  • ‘showMessage()’ displays the message.
  • In the main() function, two instances created. But both are equal.

Program:

class Singleton {

    private static Singleton in1;

    private Singleton() {} // Private constructor

    public static Singleton getInstance() {

        if (in1 == null) {

            in1 = new Singleton();

        }

        return in1;

    }

    public void showMessage() {

        System.out.println("Singleton instance is accessed here!");

    }

}

public class SDPEg {

    public static void main(String[] args) {

        Singleton ob1 = Singleton.getInstance();

        Singleton ob2 = Singleton.getInstance();

        ob1.showMessage();

        System.out.println(ob1 == ob2);

    }

}

Output:

Compile and run the above program to get the output

C:\raji\blog>javac SDPEg.java

C:\raji\blog>java SDPEg

Singleton instance is accessed here!

True

This design pattern is used in Database connections and logging.

This is the way of creating Singleton design pattern in java. Hope, it will be useful to you. Keep Coding!!!!

No comments:

Post a Comment