You are on page 1of 6

1.

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 {

private static Singleton single_instance = null;

public String s;

private Singleton()

s = "Hello I am a string part of Singleton class";

public static synchronized Singleton getInstance()

if (single_instance == null)

single_instance = new Singleton();

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 {

System.out.println( "Three objects DO NOT point to the same memory location on


the heap");

}
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?

Solution Create a Pure Fabrication object called a Factory that handles


the creation.
2. Structural Design Pattern: - It is a design pattern that defines how an object
and classes can be combined to form a structure.

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.

Problem How to resolve incompatible interfaces, or how to provide a


stable interface to similar components with different interfaces?

Solution Convert the original interface of a component into another


interface, through an intermediate adapter object.

You might also like