Category Archives: Design

Design Patterns

Design Patterns

Factory Pattern

Problem

  • Client does not know which class to instantiate when there are multiple implementations available (in case of interface/abstract class)

Solution

  • Client passes information about object
  • Based on client information, Factory instantiates specific class (concrete) and returns the object

Example

  • There is Pizza abstract class
  • CheesePizza extends Pizza
  • VeggiePizza extends Pizza
  • PizzaFactory has method Pizza createPizza(String type). If client enters “cheese”, factory will return instance of CheesePizza

AbstractFactoryPattern

Abstract Factory Pattern
Image src Youtube

Gang of Four

Factory

  • Creates various instances based upon input

Singleton

  • Creates at most one instance

Façade

  • Provides a simplified interface to complex logic

Iterator

  • Process all elements in a collection without knowing the elements’ type
Iterator Pattern

Benefits

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Use the Iterator pattern to process all elements in a collection without regards to the elements’ type
  • Polymorphic traversal (iteration)
  • This pattern supports the Single Responsibility principle and facilitate high cohesion, which is a measure of how closely a class or module supports a single purpose or responsibility.

    Liabilities

    Structure

    Structure of the Iterator Pattern

    Resources

Observer Pattern

Summary

  • Also known as Publisher Subscriber
Singleton Pattern

Summary

  • Ensures that there is one and only one instance of a class in existence at any point in time

Solution

  • Singleton class itself is responsible for creating its own instance, no other class should be allowed

Java Implementation

  • Instance variable – private static final instance = DefaultConstructor()
  • Mark constructor private
  • Define public static getInstance() method to return instance