Wednesday, September 24, 2014

Design Patterns in OOD/OOP

Definition

It is a collection of reusable solutions identified by software professionals through lesson learned and best practices to a commonly reoccurring problem in software design.

In Object Oriented Design ,Software Design Patterns are derived from Object Oriented Concepts and Principles.

Invention

Commonly called that Gang of Four are founders of design patterns

Intention

Mainly focuses on designing and developing easy to maintenance, flexible, low coupling and high cohesion applications.

Types
  1. Object Oriented Design Patterns - How the Classes and Objects are organized to develop an easy maintenance system.
  2.  Architectural Design Patterns  - How the Components (Collection of Classes) are arranged in different tiers across an enterprise application to develop an easy maintenance and scalable system.

Object Oriented Design Patterns

    Categorized into 4 sub categories.
  1. Creational  Patterns - Focuses on new object creation.
  2. Structural Patterns - Focuses on simple way to realize relationships between entities.
  3. Behavioral Patterns - Focuses on common communication relationships between objects.
  4. Concurrency Patterns - Focuses on the multi-threaded programming paradigm.

Architectural Design Patterns

  Categorized into 3 sub categories.
  1. Presentation Tier Patterns - Focuses on arranging components in front-end.
  2. Business Tier Patterns - Focuses on arranging components and interaction with Presentation Tier.
  3. Integration Tier Patterns  - Focuses on arranging components in back-end and interaction with Business Tier.

Saturday, September 20, 2014

Decorator Design Pattern

Definition

Decorator Design Pattern is a Structural Design Pattern that adds additional behavior or responsibilities to an object at runtime.

Intention
  1. Adds additional functionality to an object at runtime.
  2. Provides flexible alternative to sub classing.
  3. Works as a filter by applying criteria.
Components

Component - Interface for objects that can have additional responsibilities at runtime.
Concrete Components - Objects that are wrapped by additional behavior.
Decorator - Type of additional behavior that will wrap around Concrete Components
Concrete Decorators  - Extends the functionality of the component by adding behavior or features.
Client - The user who needs the Concrete Components to be added new responsibilities. 










Component

 public interface Vehicle {

    public void drive();

}

Concrete Components


public class Car implements Vehicle {

    @Override
    public void drive() {
        System.out.println("Drive with fuel");
    }

}



Decorator


public abstract class FuelDecorator implements Vehicle {

    protected Vehicle vehicle;

    public FuelDecorator(Vehicle vehicle) {

        this.vehicle = vehicle;
    }

    @Override
    public abstract void drive();

}



Concrete Decorators 

 public class HybridType extends FuelDecorator {

    @Override
    public void drive() {
      
         vehicle.drive();
         System.out.println("and Battery");
    }

    public HybridType(Vehicle vehicle) {
        super(vehicle);
      
    }

}

Client

public class Client {

    public static void main(String[] args) {

        Vehicle vehicle = new Car();

        vehicle.drive(); // Output: Drive with fuel

        Vehicle hybridCar = new HybridType(vehicle);
        hybridCar.drive(); // Output: Drive with fuel
                                    // and Battery

    }

}

Facade Design Pattern

Definition

Facade Pattern is a Structural Design Pattern that insulates a set of  sub systems and their interfaces to the Client by providing common, unified interface.

Intention
  1. Hides the complexity of sub systems.
  2. Reduces the network round trip calls.
  3. Decouples the sub system functions and interfaces from the Client.
Components

       Sub Systems -  A set of complex modules that collaborate to perform a functionality.
       Facade - Unified interface that Client is provided hiding the complex interaction among Sub Systems.
       Client - The User who invokes the Facade to get the function done.







In above example, Client only calls to the UserLoginFacade to login. UserLoginFacade uses Authentication module to validate the user and Authorization module to assign roles if the user is a valid one and log the actions by calling LogUser module.

In the end, Client only gets a boolean value stating that the user is allowed login or not.

Proxy Design Pattern

Definition

A Structural Design Pattern which controls the access to a heavy resource extensive object by providing surrogate object that has similar method.

Intention
  1. Can be used to control the access to an Object
  2. Deters the creation of heavy object until it required completely
  3. Reduces the number of actual object calls providing a surrogate object
Component

Subject - The common interface that implements both real and proxy objects.
Real Object - The actual object that client needs to work with.
Proxy - The object client is provided to represent the actual object hiding the complexity.
Client - The user who needs to interact with the Subject.


















Subject

public interface Loader {

    public void getFile();
}


Real Object

public class FileLoader implements Loader {
    @Override
    public void getFile(){
       
        System.out.println("Accessing the file");
    }

}
 
Proxy Object

public class ProxyFileLoader implements Loader {

    private FileLoader fileLoader;
    private boolean isAutorized;

    public ProxyFileLoader(String userName, String password) {

        if ("userA".equalsIgnoreCase(userName)
                && "passwordA".equalsIgnoreCase(password)) {
            setAutorized(true);
        }
        fileLoader = new FileLoader();
    }

    @Override
    public void getFile() {
        if (isAutorized) {
            fileLoader.getFile();
        }

        else {
            System.out.println("Cannot access the file.");
        }
    }

    public boolean isAutorized() {
        return isAutorized;
    }

    public void setAutorized(boolean isAutorized) {
        this.isAutorized = isAutorized;
    }

}

Client

public class Client {

    public static void main(String[] args) {

        Loader loader = new ProxyFileLoader("userA", "passwordA");
        loader.getFile(); // Output: Accessing the file

        Loader loaderWithIncorrectCredintials = new ProxyFileLoader(
                "wrongUser", "wrongPassword");
        loaderWithIncorrectCredintials.getFile(); // Output: Cannot access the file.
                                                   
    }

}

Composite Design Pattern

Definition

Composite design pattern is a Structural Design Pattern that provide 0 to many parent child relationship. Simply, an Object composes of similar types of objects and this second level objects could comprise similar type of objects  which structure part-whole relationship.

Intention
  • Composes objects into tree structures to represent part-whole hierarchies.
  • Lets clients treat individual objects and compositions of objects uniformly.
Components

Composite - Acts like a container that holds similar type of objects.
Leaf - Node in the hierarchy.
Component - The common interface that needs to be implemented by Composite and Leaf.
Client - Uses the Composite to traverse through the Leaves.



 Component

 public interface Shape {

    public void draw();
}

Leaf 1

public class Oval implements Shape {

    @Override
    public void draw() {
        System.out.println("This is an Oval");
    }

}

Leaf 2

public class Circle implements Shape {

    @Override
    public void draw() {
        System.out.println("This is a Circle");

    }

}

Composite

public class ShapeComposite implements Shape {

    private ArrayList<Shape> shapeList = new ArrayList<Shape>();

    @Override
    public void draw() {
        for (Shape shapeType : shapeList) {
            shapeType.draw();

        }
    }

    public void addShape(Shape shape) {
        shapeList.add(shape);
    }

    public void removeShape(Shape shape) {
        shapeList.remove(shape);
    }

    public void clearAll() {
        shapeList.clear();
    }

}


public class Client {

    public static void main(String[] args) {

        Shape circl1 = new Circle();
        Shape oval1 = new Oval();
        ShapeComposite shapeComposite = new ShapeComposite();
        ShapeComposite shapeComposite2 = new ShapeComposite();

        shapeComposite.addShape(circl1);
        shapeComposite.addShape(oval1);
        shapeComposite2.addShape(shapeComposite);
        shapeComposite2.draw(); // Output: This is a Circle
                                // This is an Oval

    }

}