A method is said to be a factory method if and only if whose return type must be similar to name of the class where it presents.
Rules for factory method:
A Singleton class is one which allows us to create only one object for JVM. Every Singleton class must contain one object on its own and it should be declared as private. Every Singleton class contains at least one factory method. Default constructor of Singleton class must be made it as private.
Write a java program which illustrates the concept of factory method and Singleton process?
Answer:
class Stest { private static Stest st; private Stest() { System.out.println("OBJECT CREATED FIRST TIME"); } public static Stest create() { if (st == null) { st = new Stest(); } else { System.out.println("OBJECT ALREADY CREATED"); } return (st); } }; class DpDemo { public static void main(String[] args) { Stest st1 = Stest.create(); Stest st2 = Stest.create(); Stest st3 = Stest.create(); if ((st1 == st2) && (st2 == st3) && (st3 == st1)) { System.out.println("ALL OBJECTS ARE SAME"); } else { System.out.println("ALL OBJECTS ARE NOT SAME"); } } };