Java Tutorial

Design Patterns

Design Patterns:

Design patterns are set of predefined proved rules by industry experts to avoid recurring problems which are occurring in software development. As a part of information technology we have some hundreds of design patterns but as a part of J2SE so far we have two types of design patterns. They are factory method and Singleton class.

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:

  1. Every factory method must be public method.
  2. Every factory method must be similar to name of the class where it presents.

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?


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");