Design Pattern

Creational Patterns - Factory Pattern
Creational Patterns - Abstract Factory Pattern
Creational Patterns -What is Singleton Pattern?
Creational Patterns - What is Builder Pattern?
Creational Patterns - What is Prototype Pattern?
Structural Patterns -What is Facade Design Pattern?
Structural Patterns - Adapter Pattern
Structural Patterns - Bridge Pattern
Structural Patterns - Composite Pattern
Structural Patterns - Decorator Pattern
Behavioral Patterns - Command Pattern
Behavioral Patterns - Interpreter Pattern
Behavioral Patterns - Iterator Pattern

Creational Patterns - Factory Pattern
  • A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.
  • A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.
  • In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.
  • Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.
Sample Java Source Code for Factory Method Design Pattern

Base class:

//super class that serves as type to be instantiated for factory method pattern
public interface Pet {

public String speak();

}

First subclass:

//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {

public String speak() {
return "Bark bark...";
}
}

Second subclass:

//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
public String speak() {
return "Quack quack...";
}
}

Factory class:

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

public Pet getPet(String petType) {
Pet pet = null;

// based on logic factory instantiates an object
if ("bark".equals(petType))
pet = new Dog();
else if ("quack".equals(petType))
pet = new Duck();
return pet;
}
}

Using the factory method to instantiate

//using the factory method pattern
public class SampleFactoryMethod {

public static void main(String args[]){

//creating the factory
PetFactory petFactory = new PetFactory();

//factory instantiates an object
Pet pet = petFactory.getPet("bark");

//you don't know which object factory created
System.out.println(pet.speak());
}

}
Output of the above sample program for Factory Method Pattern

Bark bark

Creational Patterns - Abstract Factory Pattern
  • This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.
  • Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.
Creational Patterns -What is Singleton Pattern?
  • Singleton Pattern says that just "define a class that has only one instance and provides a global point of access to it".
public class OnlyOne {
private static OnlyOne one = new OnlyOne();
private OnlyOne() {… } //private constructor. This class cannot be  instantiated from outside.
public static OnlyOne getInstance() {
return one;
}
}
To use it:
//No matter how many times you call, you get the same instance of the object.
OnlyOne myOne = OnlyOne.getInstance();
Note: 
  • The constructor must be explicitly declared and should have the private access modifier, so that it cannot be instantiated from out side the class. The only way to instantiate an instance of class OnlyOne is through the getInstance() method with a public access modifier.
  • A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
Creational Patterns - What is Builder Pattern?
  • Builder Pattern says that "construct a complex object from simple objects using step-by-step approach".
  • It is mostly used when object can't be created in single step like in the de-serialization of a complex object.
Creational Patterns - What is Prototype Pattern?
  • The prototype means making a clone.
  • Prototype Pattern says that cloning of an existing object instead of creating new one and can also be customized as per the requirement.
  • This pattern should be followed, if the cost of creating a new object is expensive and resource intensive.
  • We use the interface Cloneable and call its method clone() to clone the object.
Structural Patterns -What is Facade Design Pattern?
  • Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.
  • Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. 
  • This type of design pattern comes under structural pattern as this pattern adds an interface to exiting system to hide its complexities.
  • This pattern involves a single class which provides simplified methods which are required by client and delegates calls to existing system classes methods.
  • In Java, the interface JDBC can be called a facade. We as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver.
Example1
This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

/* Complex parts */
 
class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }}
 
class Memory {
    public void load(long position, byte[] data) { ... }}
 
class HardDrive {
    public byte[] read(long lba, int size) { ... }}
 
/* Facade */
 
class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;
 
    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }
 
    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }}
 
/* Client */
 
class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }}
Example2
We're going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step.
ShapeMaker class uses the concrete classes to delegates user calls to these classes. FacadePatternDemo, our demo class will use ShapeMaker class to show the results.
Facade Pattern UML Diagram

Step 1

Create an interface.
Shape.java
public interface Shape {
   void draw();}

Step 2

Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Rectangle::draw()");
   }}
Square.java
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Square::draw()");
   }}
Circle.java
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Circle::draw()");
   }}

Step 3

Create a facade class.
ShapeMaker.java
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();
   }}

Step 4

Use the facade to draw various types of shapes.
FacadePatternDemo.java
public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();              
   }}

Step 5

Verify the output.
Circle::draw()
Rectangle::draw()
Square::draw()
Structural Patterns - Adapter Pattern
  • The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.
  • Let’s try and understand this with the help of an example. Again, I will like to take a general example. We all have electric sockets in our houses of different sizes and shapes. I will take an example of a socket of 15 Ampere. This is a bigger socket and the other one which is smaller is of 5 Ampere. A 15 Amp plug cannot fit into a 5 Amp socket. Here, we will use an Adapter. The adapter can be called a connector here. The connector connects both of these and gives output to the client plug which is of 5 Amp.
  • The Adapter is something like this. It will be having the plug of suitable for 15 Amp and a socket suitable for a 5 Amp plug. So, that the 5 Amp plug which here is the client can fit in and also the server which here is the 15 Amp socket can give the output.
Structural Patterns - Bridge Pattern
  • The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.
  • The best example for this is like the electric equipments you have at home and their switches. For e.g., the switch of the fan. The switch is the interface and the actual implementation is the Running of the fan once its switched-on. Still, both the switch and the fan are independent of each other. Another switch can be plugged in for the fan and this switch can be connected to light bulb.
Structural Patterns - Composite Pattern
  • A Composite Pattern says that just "allow clients to operate in generic manner on objects that may or may not represent a hierarchy of objects".
  • In developing applications, we come across components which are individual objects and also can be collection of objects. Composite pattern can represent both the conditions. In this pattern, you can develop tree structures for representing part-whole hierarchies.
  • The most common example in this pattern is of a company’s employee hierarchy. We here will also take the same example.
  • The employees of a company are at various positions. Now, say in a hierarchy, the manager has subordinates; also the Project Leader has subordinates, i.e. employees reporting to him/her. The developer has no subordinates.
Structural Patterns - Decorator Pattern
  • A Decorator Pattern says that just "attach a flexible additional responsibilities to an object dynamically".
  • Decorator pattern allows to add new functionality an existing object without altering its structure. This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.
  • In other words, The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime.
  • The Decorator Pattern is also known as Wrapper.
Behavioral Patterns - Command Pattern
  • This is another of the data-driven pattern. The client invokes a particular module using a command. The client passes a request, this request gets propagated as a command. The command request maps to particular modules. According to the command, a module is invoked.
  • It’s like there is a server having a lot of services to be given, and on Demand (or on command), it caters to that service for that particular client.
  • A classic example of this is a restaurant. A customer goes to restaurant and orders the food according to his/her choice. The waiter/ waitress takes the order (command, in this case) and hands it to the cook in the kitchen. The cook can make several types of food and so, he/she prepares the ordered item and hands it over to the waiter/waitress who in turn serves to the customer.
Behavioral Patterns - Interpreter Pattern
  • The Interpreter Pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. The best example you can get for this is Java itself which is an interpreted language. It converts the code written in English to a byte code format so as to make possible for all the operating systems to understand it. This quality of it makes it platform independent.
  • SQL Parsing uses interpreter design pattern.
Behavioral Patterns - Iterator Pattern
  • This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. 
  • Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data.
  • We use iterators quite frequently in everyday life. For example, remote control of TV. Any remote control we use, either at home/hotel or at a friend’s place, we just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels.



No comments:

Post a Comment