Pages

Design Patterns


1. Singleton Design Pattern


Definition : Singleton class means that any given time only one instance of the class is present in one JVM.

Real Time Example : Present of a Country

Different between Singleton Class and Static Members

1. Singleton is an object whereas static is not an object.
2. Singleton can be extended/sub-classed whereas static cannot be extended/sub classed.
3. Singleton can be passed around as an object whereas static cannot be passed around as an object.
4. Singleton can be garbage collected whereas static cannot be garbage collected.
5. Static provides better performance than singleton class.
6. Static methods are bounded on compiler time whereas singleton class are bounded on runtime.
7. Static method can not be overridden by extending.
8. Singleton class is a design pattern whereas static is a keyword.
package com.jaladhi;

public class Singleton {
      private static Singleton instance;
      private Singleton() { }
      public static Singleton getInstance() {
            if(instance == null) {
                  instance = new Singleton();
            }
            return instance;
      }
      public static void main(String [ ] args) {
            System.out.println("Object 1 : " + Singleton.getInstance());
            System.out.println("Object 2 : " + Singleton.getInstance());
      }
}

2. Singleton Class using Inner Class


package com.jaladhi;

public class Singleton {
      private Singleton ( ) { }
      private static class SingletonHolder {
            private static final Singleton INSTANCE = new Singleton ( );
      }
      public static Singleton getInstance ( ) {
            return SingletonHolder.INSTANCE;
      }
}

3. Singleton Class using Eager Initialization


package com.jaladhi;

public class EagerInitialization {
      private static final EagerInitialization instance = new EagerInitialization ();
      private EagerInitialization () { }
      public static EagerInitialization getInstance ( ) {
            return instance;
      }
}

4. Singleton Class Using Static Block


package com.jaladhi;

public class StaticBlock {
      public static StaticBlock instance;
      private StaticBlock ( ) { }
      static {
            instance = new StaticBlock ( );
      }
}

5. Singleton Class Using Lazy Initialization


package com.jaladhi;

public class LazyInitialization {
      private static LazyInitialization instance;
      private LazyInitialization ( ) { }
      public static LazyInitialization getInstance() {
            if (instance == null) {
                  instance = new LazyInitialization ( );
            }
            return instance;
      }
}

6. Singleton Class Using Thread Safe


package com.jaladhi;

public class ThreadSafe {
      private static ThreadSafe instance;
      private ThreadSafe () { }
      synchronized public static ThreadSafe getInstance() {
            if (instance == null) {
                  instance = new ThreadSafe ( );
            }
            return instance;
      }
}

7. Singleton Class Using Synchorinzed Block


package com.jaladhi;

public class SynchorinzedBlock {
      private static SynchorinzedBlock instance;
      private SynchorinzedBlock ( ) { }
      public static SynchorinzedBlock getInstance () {
            if (instance == null) {
                  synchronized (SynchorinzedBlock.class) {
                        if(instance==null) {
                              instance = new SynchorinzedBlock ();
                        }
                  }
            }
            return instance;
      }
}

8. Doubleton Design Pattern


Definition : Doubleton class means that any given time only two instance of the class is present in one JVM.

package com.jaladhi;

public class Doubleton {
      private static Doubleton firstInstance;
      private static Doubleton secondInstance;
      private Doubleton() { }
      public static Doubleton getInstance() {
            if(firstInstance == null) {
                  firstInstance = new Doubleton();
                  return firstInstance;
            } else if(secondInstance == null) {
                  secondInstance = new Doubleton();
                  return secondInstance;
            } else {
                  if(Math.random() < 0.5) {
                        return firstInstance;
                  } else {
                        return secondInstance;
                  }
            }
      }
      public static void main(String [ ] args) {
            System.out.println("Object 1 : " + Doubleton.getInstance());
            System.out.println("Object 2 : " + Doubleton.getInstance());
            System.out.println("Object 3 : " + Doubleton.getInstance());
            System.out.println("Object 4 : " + Doubleton.getInstance());
      }
}

9. Tripleton Design Pattern


Definition : Tripleton class means that any given time only three instance of the class is present in one JVM.

package com.jaladhi;

public class Tripleton {
      private static Tripleton instance;
      public static int objCount = 0;
      private Tripleton() {
            objCount++;       }
      public static Tripleton getInstance() {
            if(objCount < 3) {
                  instance = new Tripleton();
            }
            return instance;
      }
      public static void main(String [ ] args) {
            System.out.println("Object 1 : " + Tripleton.getInstance());
            System.out.println("Object 2 : " + Tripleton.getInstance());
            System.out.println("Object 3 : " + Tripleton.getInstance());
            System.out.println("Object 4 : " + Tripleton.getInstance());
            System.out.println("Object 5 : " + Tripleton.getInstance());
            System.out.println("Object 6 : " + Tripleton.getInstance());
      }
}

10. Factory Design Pattern


Real Time Example : In an organization HR Works as Factory Method. Here Development Team request types of resources need to HR based on request type. HR provides resource to Development team.

package com.jaladhi;

public interface Shape {
      void draw();
}
public class Rectangle implements Shape {
      @Override
      public void draw() {
            System.out.println("Inside Rectangle::draw() method.");
      }
}
public class Square implements Shape {
      @Override
      public void draw() {
            System.out.println("Inside Square::draw() method.");
      }
}
public class Circle implements Shape {
      @Override
      public void draw() {
            System.out.println("Inside Circle::draw() method.");
      }
}
public class ShapeFactory {
      public Shape getShape(String shapeType){
            if(shapeType == null){
                  return null;
            }
            if(shapeType.equalsIgnoreCase("CIRCLE")){
                  return new Circle();
            } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
                  return new Rectangle();
            } else if(shapeType.equalsIgnoreCase("SQUARE")){
                  return new Square();
            }
            return null;
      }
}
public class FactoryPatternDemo {
      public static void main(String[] args) {
            ShapeFactory shapeFactory = new ShapeFactory();
            Shape shape1 = shapeFactory.getShape("CIRCLE");
            shape1.draw();
            Shape shape2 = shapeFactory.getShape("RECTANGLE");
            shape2.draw();
            Shape shape3 = shapeFactory.getShape("SQUARE");
            shape3.draw();
      }
}

11. Abstract Factory Design Pattern

package com.jaladhi;

public interface Bank{
      String getBankName();
}
public class HDFC implements Bank {
      private final String BNAME;
      public HDFC(){
            BNAME = "HDFC BANK";
      }
      public String getBankName() {
            return BNAME;
      }
}
public class ICICI implements Bank {
      private final String BNAME;
      public ICICI(){
            BNAME = "ICICI BANK";
      }
      public String getBankName() {
            return BNAME;
      }
}
public class SBI implements Bank{
      private final String BNAME;
      public SBI(){
            BNAME="SBI BANK";
      }
      public String getBankName(){
            return BNAME;
      }
}
public abstract class Loan{
      protected double rate;
      abstract void getInterestRate(double rate);
      public void calculateLoanPayment(double loanamount, int years) {
            double EMI;
            int n;
            n = years*12;
            rate = rate/1200;
            EMI = ((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount;
            System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have borrowed");
      }
}
public class HomeLoan extends Loan{
      public void getInterestRate(double r){
            rate = r;
      }
}
public class BussinessLoan extends Loan{
      public void getInterestRate(double r){
            rate = r;
      }
}
public class EducationLoan extends Loan{
      public void getInterestRate(double r){
            rate = r;
      }
}
public abstract class AbstractFactory{
      public abstract Bank getBank(String bank);
      public abstract Loan getLoan(String loan);
}
public class BankFactory extends AbstractFactory{
      public Bank getBank(String bank){
            if(bank == null){
                  return null;
            }
            if(bank.equalsIgnoreCase("HDFC")){
                  return new HDFC();
            } else if(bank.equalsIgnoreCase("ICICI")){
                  return new ICICI();
            } else if(bank.equalsIgnoreCase("SBI")){
                  return new SBI();
            }
            return null;
      }
      public Loan getLoan(String loan) {
            return null;
      }
}
public class LoanFactory extends AbstractFactory{
      public Bank getBank(String bank){
            return null;
      }
      public Loan getLoan(String loan){
            if(loan == null){
                  return null;
            }
            if(loan.equalsIgnoreCase("Home")){
                  return new HomeLoan();
            } else if(loan.equalsIgnoreCase("Business")){
                  return new BussinessLoan();
            } else if(loan.equalsIgnoreCase("Education")){
                  return new EducationLoan();
            }
      return null;
      }
}
public class FactoryCreator {
      public static AbstractFactory getFactory(String choice){
            if(choice.equalsIgnoreCase("Bank")){
                  return new BankFactory();
            } else if(choice.equalsIgnoreCase("Loan")){
                  return new LoanFactory();
            }
      return null;
      }
}
public class AbstractFactoryPatternExample {
      public static void main(String args[])throws IOException {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the name of Bank from where you want to take loan amount: ");
            String bankName=br.readLine();
            System.out.print("\n");
            System.out.print("Enter the type of loan e.g. home loan or business loan or education loan : ");
            String loanName=br.readLine();
            AbstractFactory bankFactory = FactoryCreator.getFactory("Bank");
            Bank b=bankFactory.getBank(bankName);
            System.out.print("\n");
            System.out.print("Enter the interest rate for "+b.getBankName()+ ": ");
            double rate=Double.parseDouble(br.readLine());
            System.out.print("\n");
            System.out.print("Enter the loan amount you want to take: ");
            double loanAmount=Double.parseDouble(br.readLine());
            System.out.print("\n");
            System.out.print("Enter the number of years to pay your entire loan amount: ");
            int years=Integer.parseInt(br.readLine());
            System.out.print("\n");
            System.out.println("you are taking the loan from "+ b.getBankName());
            AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");
            Loan l=loanFactory.getLoan(loanName);
            l.getInterestRate(rate);
            l.calculateLoanPayment(loanAmount,years);
      }
}

12. Facade Design Pattern

package com.jaladhi;

public interface Shape {
      void draw();
}
public class Rectangle implements Shape {
      @Override
      public void draw() {
            System.out.println("Rectangle::draw() method.");
      }
}
public class Square implements Shape {
      @Override
      public void draw() {
            System.out.println("Square::draw() method.");
      }
}
public class Circle implements Shape {
      @Override
      public void draw() {
            System.out.println("Circle::draw() method.");
      }
}
public class ShapeMaker {
      private Shape circle;
      private Shape rectangle;
      private Shape square;
      public ShapeMaker() {
            circle = new Circle();
            rectangle = new Rectangle();
            square = new Square();
      }
      public void drawCircle(){
            circle.draw();
      }
      public void drawRectangle(){
            rectangle.draw();
      }
      public void drawSquare(){
            square.draw();
      }
}
public class FacadePatternDemo {
      public static void main(String[] args) {
            ShapeMaker shapeMaker = new ShapeMaker();
            shapeMaker.drawCircle();
            shapeMaker.drawRectangle();
            shapeMaker.drawSquare();
      }
}

13. MVC (Model, View And Controller) Design Pattern

package com.jaladhi;

public class Student {
      private String name;
      private int rollNo;
      public Student(String name, int rollNo){
            this.name = name;
            this.rollNo = rollNo;
      }
      public String getName() {
            return name;
      }
      public void setName(String name) {
            this.name = name;
      }
      public int getRollNo() {
            return rollNo;
      }
      public void setRollNo(int rollNo) {
            this.rollNo = rollNo;
      }
}
public class StudentView {
      public void printStudentDetails(String studentName, String studentRollNo){
            System.out.println("Student: ");
            System.out.println("Name: " + studentName);
            System.out.println("Roll No: " + studentRollNo);
      }
}
public class StudentController {
      private Student model;
      private StudentView view;
      public StudentController(Student model, StudentView view){
            this.model = model;
            this.view = view;
      }
      public void setStudentName(String name){
            model.setName(name);
      }
      public String getStudentName(){
            return model.getName();
      }
      public void setStudentRollNo(String rollNo){
            model.setRollNo(rollNo);
      }
      public String getStudentRollNo(){
            return model.getRollNo();
      }
      public void updateView(){
            view.printStudentDetails(model.getName(), model.getRollNo());
      }
}
public class MVCPatternDemo {
      public static void main(String[] args) {
            Student model = retriveStudentFromDatabase();
            StudentView view = new StudentView();
            StudentController controller = new StudentController(model, view);
            controller.updateView();
            controller.setStudentName("John");
            controller.updateView();
      }
      private static Student retriveStudentFromDatabase(){
            Student student = new Student();
            student.setName("Robert");
            student.setRollNo("10");
            return student;
      }
}

14. DAO (Data Access Object) Design Pattern

package com.jaladhi;

public class Student {
      private String name;
      private int rollNo;
      public Student(String name, int rollNo){
            this.name = name;
            this.rollNo = rollNo;
      }
      public String getName() {
            return name;
      }
      public void setName(String name) {
            this.name = name;
      }
      public int getRollNo() {
            return rollNo;
      }
      public void setRollNo(int rollNo) {
            this.rollNo = rollNo;
      }
}
import java.util.List;
public interface StudentDao {
      public List getAllStudents();
      public Student getStudent(int rollNo);
      public void updateStudent(Student student);
      public void deleteStudent(Student student);
}
import java.util.ArrayList;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
      public List students;
      public StudentDaoImpl(){
            students = new ArrayList();
            Student student1 = new Student("Robert",0);
            Student student2 = new Student("John",1);
            students.add(student1);
            students.add(student2);
      }
      @Override
      public void deleteStudent(Student student) {
            students.remove(student.getRollNo());
            System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
      }
      @Override
      public List getAllStudents() {
            return students;
      }
      @Override
      public Student getStudent(int rollNo) {
            return students.get(rollNo);
      }
      @Override
      public void updateStudent(Student student) {
            students.get(student.getRollNo()).setName(student.getName());
            System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the database");
      }
}
public class DaoPatternDemo {
      public static void main(String[] args) {
            StudentDao studentDao = new StudentDaoImpl();
            for(Student student : studentDao.getAllStudents()) {
                  System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
            }
            Student student = studentDao.getAllStudents().get(0);
            student.setName("Michael");
            studentDao.updateStudent(student);
            studentDao.getStudent(0);
            System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }
}

15. DTO (Data Transfer Object) Design Pattern

package com.jaladhi;
public class StudentVO {
      private String name;
      private int rollNo;
      public StudentVO(String name, int rollNo){
            this.name = name;
            this.rollNo = rollNo;
      }
      public String getName() {
            return name;
      }
      public void setName(String name) {
            this.name = name;
      }
      public int getRollNo() {
            return rollNo;
      }
      public void setRollNo(int rollNo) {
            this.rollNo = rollNo;
      }
}
import java.util.ArrayList;
import java.util.List;
public class StudentBO {
      List students;
      public StudentBO(){
            students = new ArrayList();
            StudentVO student1 = new StudentVO("Robert",0);
            StudentVO student2 = new StudentVO("John",1);
            students.add(student1);
            students.add(student2);
      }
      public void deleteStudent(StudentVO student) {
            students.remove(student.getRollNo());
            System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
      }
      public List getAllStudents() {
            return students;
      }
      public StudentVO getStudent(int rollNo) {
            return students.get(rollNo);
      }
      public void updateStudent(StudentVO student) {
            students.get(student.getRollNo()).setName(student.getName());
            System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database");
      }
}
public class TransferObjectPatternDemo {
      public static void main(String[] args) {
            StudentBO studentBusinessObject = new StudentBO();
            for (StudentVO student : studentBusinessObject.getAllStudents()) {
                  System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
            }
            StudentVO student = studentBusinessObject.getAllStudents().get(0);
            student.setName("Michael");
            studentBusinessObject.updateStudent(student);
            student = studentBusinessObject.getStudent(0);
            System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }
}