Professional Documents
Culture Documents
Creational Design Pattern: It is a design pattern that deals with an object creation
mechanism, trying to create object in a manner suitable to the situation.
1.1 Singleton Pattern Demo: The singleton pattern is a design pattern used to implement the
mathematical concept of a singleton, by restricting the instantiation of a class to one object.
This is useful when exactly one object is needed to coordinate actions across the system.
Name: Factory
Problem: How can be guaranteed that on one and only one instances of a class can be
created? Solution: Create a class with a class operation get Instance().
class Singleton {
public String s;
private Singleton()
if (single_instance == null)
return single_instance;
Main class
class Shady{
public static void main(String args[])
Singleton x = Singleton.getInstance();
Singleton y = Singleton.getInstance();
Singleton z = Singleton.getInstance();
System.out.println("Hashcode of x is "
+ x.hashCode());
System.out.println("Hashcode of y is "
+ y.hashCode());
System.out.println("Hashcode of z is "
+ z.hashCode());
if (x == y && y == z) {
System.out.println( "Three objects point to the same memory location on the heap i.e, to the
same object");
else {
}
1.2 Factory Pattern: - It provides a way to use an instance as object factory. Then the factory
returns a instance of one of several possible classes depending on the data provided to it. In
Factory pattern, we create object without exposing the creation logic to the client and refer to
newly created object using a common interface.
Problem Who should be responsible for creating objects when there
are special considerations such as complex creation logic, a
desire to separate creation responsibilities for better
cohesion?
2.1 Adapter Pattern: - This pattern works as a bridge between two incompatible interfaces. This
pattern involves a single class which is responsible to join functionalities of independent or
incompatible interfaces.