Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, 15 November 2018

Structural design patterns are concerned with how classes and objects can be composed, to form larger structures.The structural design patterns simplifies the structure by identifying the relationships.These patterns focus on, how the classes inherit from each other and how they are composed from other classes.

  • Adapter Pattern 
    • An Adapter Pattern says that just "converts the interface of a class into another interface that a client wants".
    • In other words, to provide the interface according to client requirement while using the services of a class with a different interface.
    • The Adapter Pattern is also known as Wrapper.

Thursday, 11 October 2018


  • S.O.L.I.D is an acronym for the first five object-oriented design(OOD) principles by Robert C. Martin, popularly known as Uncle Bob.
  • These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend
  • They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.
    • S - Single-responsiblity principle
    • O - Open-closed principle
    • L - Liskov substitution principle
    • I - Interface segregation principle
    • D - Dependency Inversion Principle
  • Single-responsibility Principle(like Encapsulation)
    • A class should have one and only one reason to change, meaning that a class should have only one job.
    • SOLID Principles and Design Patterns plays a key role in achieving all of the above points.
      • Each class and module should focus on a single task at a time
      • Everything in the class should be related to that single purpose
      • There can be many members in the class as long as they related to the single responsibility
      • With SRP, classes become smaller and cleaner
      • Code is less fragile
      • class Circle { public $radius; public function **construct($radius) { $this->radius = $radius; } } class Square { public $length; public function **construct($length) { $this->length = $length; } }
  • Open-closed Principle(like Abstraction)
    • Objects or entities should be open for extension, but closed for modification.
    • This simply means that a class should be easily extendable without modifying the class itself. 
    • Implementation
      •  The simplest way to apply OCP is to implement the new functionality on new derived (sub) classes that inherit the original class implementation.
      • Another way is to allow client  to access the original class with an abstract interface
  • Liskov substitution principle(like Aggregation)
    • Substitutability is a principle in object-oriented programming and it states that, in a computer program, if S is a Subtype of T, then objects of type T may be replaced with objects of type S
    •  This principle is just an extension of the Open Close Principle 
  • Interface segregation principle(avoid unused methods from interface)
    • The interface-segregation principle (ISP) states that "no client should be forced to depend on methods it does not use".
    • Which means, Instead of one fat interface many small interfaces are preferred based on groups of methods with each one serving one submodule 
  • Dependency Inversion principle
    • High-level modules should not depend on low-level modules. Both should depend on abstractions.
    • Abstractions should not depend on concrete. Concrete should depend on abstractions.
    • Exmaple:
      • The PasswordReminder class should not care what database your application uses, to fix this again we "code to an interface", since high level and low level modules should depend on abstraction, we can create an interface:

Tuesday, 9 October 2018


  • Prototype pattern refers to creating duplicate object 
  • This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.
  • // Prototype pattern public abstract class Prototype implements Cloneable { public Prototype clone() throws CloneNotSupportedException{ return (Prototype) super.clone(); } } public class ConcretePrototype1 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype1)super.clone(); } } public class ConcretePrototype2 extends Prototype { @Override public Prototype clone() throws CloneNotSupportedException { return (ConcretePrototype2)super.clone(); } }


  • This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.
  • SingleObject class have its constructor as private and have a static instance of itself.                                         
  1. Create a Singleton Class.
public class SingleObject { //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } }
  1. Get the only object from the singleton class.
public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject(); //Get the only object available SingleObject object = SingleObject.getInstance(); //show the message object.showMessage(); } }

  • Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
  • In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.
  • We are going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We create an abstract factory class AbstractFactory as next step. Factory classes ShapeFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.
  • Step 1
  • public interface Shape { void draw(); }
  • Step 2
  • 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."); } }
  • Step 3
  • public interface Color { void fill(); }
  • Step 4
  • public class Red implements Color { @Override public void fill() { System.out.println("Inside Red::fill() method."); } }

  • public class Blue implements Color { @Override public void fill() { System.out.println("Inside Blue::fill() method."); } }

  • public class Green implements Color { @Override public void fill() { System.out.println("Inside Green::fill() method."); } }
  • Step 5
  • public abstract class AbstractFactory { abstract Color getColor(String color); abstract Shape getShape(String shape) ; }
  • Step 6
  • public class ShapeFactory extends AbstractFactory { @Override 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; } @Override Color getColor(String color) { return null; } }

  • public class ColorFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ return null; } @Override Color getColor(String color) { if(color == null){ return null; } if(color.equalsIgnoreCase("RED")){ return new Red(); }else if(color.equalsIgnoreCase("GREEN")){ return new Green(); }else if(color.equalsIgnoreCase("BLUE")){ return new Blue(); } return null; } }
  • Step 7
  • public class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("SHAPE")){ return new ShapeFactory(); }else if(choice.equalsIgnoreCase("COLOR")){ return new ColorFactory(); } return null; } }
  • Step 8
  • public class AbstractFactoryPatternDemo { public static void main(String[] args) { //get shape factory AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE"); //get an object of Shape Circle Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Shape Circle shape1.draw(); //get an object of Shape Rectangle Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Shape Rectangle shape2.draw(); //get an object of Shape Square Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of Shape Square shape3.draw(); //get color factory AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR"); //get an object of Color Red Color color1 = colorFactory.getColor("RED"); //call fill method of Red color1.fill(); //get an object of Color Green Color color2 = colorFactory.getColor("Green"); //call fill method of Green color2.fill(); //get an object of Color Blue Color color3 = colorFactory.getColor("BLUE"); //call fill method of Color Blue color3.fill(); } }
  • Step 2



  • The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.
  • Design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
  • The Factory Method design pattern solves problems like
    • How can an object be created so that subclasses can redefine which class to instantiate?
  • Creating an object directly within the class that requires (uses) the object is inflexible because it commits the class to a particular object and makes it impossible to change the instantiation independently from (without having to change) the class.
  • Factory Method design pattern will,
    • Define a separate operation (factory method) for creating an object.
    • Create an object by calling a factory method.
  • In this way subcalss can redefine which class to initiate

  • Step 1
    • Create an interface.
    • 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("Inside Rectangle::draw() method."); } }
    • Square.java
    • 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."); } }
        
  • Step 3
    • Create a Factory to generate object of concrete class based on given information
    • ShapeFactory.java
    • public class ShapeFactory { //use getShape method to get object of type shape 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; } }
  • Step 4
    • Use the Factory to get object of concrete class by passing an information such as type.
    • FactoryPatternDemo.java
    • public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of square shape3.draw(); } }


    • The Builder is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. 
    • The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
    • The Builder design pattern solves problems like
      • Create different representations of a complex object
      • Creating a complex object be simplified
    sasasasasasasa
    /** * Represents the product created by the builder. */ class Car { private int wheels; private String color; public Car() { } public String getColor() { return color; } public void setColor(final String color) { this.color = color; } public int getWheels() { return wheels; } public void setWheels(final int wheels) { this.wheels = wheels; } @Override public String toString() { return "Car [wheels = " + wheels + ", color = " + color + "]"; } } /** * The builder abstraction. */ interface CarBuilder { Car build(); CarBuilder setColor(final String color); CarBuilder setWheels(final int wheels); } class CarBuilderImpl implements CarBuilder { private Car car; public CarBuilderImpl() { car = new Car(); } @Override public Car build() { return car; } @Override public CarBuilder setColor(final String color) { car.setColor(color); return this; } @Override public CarBuilder setWheels(final int wheels) { car.setWheels(wheels); return this; } } public class CarBuildDirector { private CarBuilder builder; public CarBuildDirector(final CarBuilder builder) { this.builder = builder; } public Car construct() { return builder.setWheels(4) .setColor("Red") .build(); } public static void main(final String[] arguments) { final CarBuilder builder = new CarBuilderImpl(); final CarBuildDirector carBuildDirector = new CarBuildDirector(builder); System.out.println(carBuildDirector.construct()); } }
    • Steps:
      • Create car builder interface
      • Car builder implementation
        • Create car object in constructor and use this object for all car object manipulation like buildCar, setCarColour ,setCarWheel etc
      • Create CarBuildDirector class with
        • initiate car builder object
        • create car using car builder methods like below
          • car builder.buildcar.setWheels(2).setColor("Red")
    • Advantages
      • Allows you to vary a product’s internal representation.
      • Encapsulates code for construction and representation.
      • Provides control over steps of construction process.
    • Disadvantages
      • Requires creating a separate ConcreteBuilder for each different type of product.
      • Requires the builder classes to be mutable.
      • Data members of class aren't guaranteed to be initialized.
      • Dependency injection may be less supported.



    • Creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation
    • The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
    • Creational design patterns are composed of two dominant ideas.
      • Encapsulating knowledge about which concrete classes the system uses.
      • Hiding how instances of these concrete classes are created and combined.
    • Creational design patterns are further categorized as
      • Object-creational patterns
        • Object-creational patterns deal with Object creation.
        • Object creation to another object
      • Class-creational patterns
        • Class-creational patterns deal with Class-instantiation.
        • Object creation to subclasses.
    • Five well-known design patterns that are parts of creational patterns are the
      • Builder pattern
        • Separate the construction of a complex object from its representation so that the same construction process can create different representations
      • Factory method pattern
        • Centralize creation of an object of a specific type choosing one of several implementations
      • Abstract factory pattern
        • A class requests the objects it requires from a factory object instead of creating the objects directly
      • Singleton pattern
        • Restrict instantiation of a class to one object
      • Prototype pattern
        • Used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects
      • Dependency Injection pattern
        • A accepts the objects it requires from an injector instead of creating the objects directly

    Search This Blog

    Contact us

    Name

    Email *

    Message *