Apr 25, 2017

Creational Design Patterns - Singleton

Singleton Pattern


Singleton pattern ensure that only one instance is initiating at the java virtual machine (JVM). That means only one object is created at the jvm and more then one object can't exist in jvm. This type of approach is used for use of resource like JDBC connections, files. JDBC connnection openning at on demand is high cost, so we should initiate jdbc connection onece. So lets see how to implement single pattern in java. So there are different ways to implement singleton in java. Based on the requirement you can choose what type of singleton pattern you should use.

Eager initialization

the instance of Singleton Class is created at the time of class loading. If we use this method, whather we use or not the object, object is created. it is not good. SO if we use the object at starting of the program use this approach. Let see how to implemnt this kind of singleton pattern

                            
public class SingletonEager {
    private static final SingletonEager instance = new SingletonEager();
    //private constructor to avoid client applications to use constructor
    private SingletonEager(){}
          public static SingletonEager getInstance(){
             return instance;
          }
    }
                            
                        

Here there is a private static variable it get initiated at the startup of the program. Becase static variables are created at the class loading

Design pattern with Java

What is Design pattern ?


A design pattern is a well described solution to a common software problem. Some problems are re occuring when developing softwares.Design patterns provides industry standard approach to solve a recurring problem, so it saves time if we sensibly use the design pattern. Design patterns promotes reusability that leads to more robust and highly maintainable code. For this tutorial we use java language. So we will learn java based design patterns.

Categories of Design Patterns



Creational Design Patterns


Creation design patterns use for object creations. Some situation objects should initiate in different ways. for example object should create when the JVM instance is up or object create on demand or else object should initiate with certain restrictions. So creation design patter used for creating objects.

Structural patterns


Structural patterns ease the design by identifying a simple way to realize relationships between entities.Structural patterns provide different ways to create a class structure, as example using inheritance and composition to create a large object from small objects.

Behavioral patterns


Behavioral patterns provide solution for the better interaction between objects and how to provide lose coupling and flexibility to extend easily. The implementation and the client should be loosely coupled in order to avoid hard coding and dependencies