Creational Design Pattern: Singleton Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Creational Design Pattern: Singleton Pattern

Share This


Using this design pattern multiple object creation of a class is restricted.

If you create and define a class, as you have defined previously, the constructors are generally public. Thus multiple instances of that class can be created. If you want to restrict the number of instance creation of a class, a policy needs to be imposed.

Here, the only way is to make the constructor private and define a method that will track the number of objects. Thus this method should be a static method.

In the following code, the variable instance_flag is set by false as no object is created at the beginning. Thus, getInstance method creates an object. When an instance is already created, the flag is true. Hence, the getInstance method returns null. So, more than one object of this class can not be created.
Source code of MyClass.java
public class MyClass { static boolean instance_flag = false; private MyClass() { } static public MyClass getInstance() { if (!instance_flag) { instance_flag = true; return new MyClass(); } else return null; } public void finalize() { instance_flag = false; } }
Source code of TestMain.java
public class TestMain { public static void main(String[] args) { MyClass mc1, mc2; System.out.println("Opening one object"); mc1 = MyClass.getInstance(); if (mc1 != null) System.out.println("got 1 object"); System.out.println("Opening two object"); mc2 = MyClass.getInstance(); if (mc2 == null) System.out.println("no instance available"); } }

Happy Exploring!

No comments:

Post a Comment