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

Friday, December 19, 2014

Adapter Design Pattern - Simple tutorial with an example in Java

Adapter Design Pattern belongs to the Structural Design Patterns group. You can use this pattern when you need to plug your existing code base to another code base which is not fully compatible with your existing code base. In such cases this pattern guarants the minimal change to your existing code.
Below I am showing you a very simple example which illustrates the use of this pattern. But note that in real world there are more complex situations where this pattern is used.

Assume that you have StudentData class which contains a list of ages of students.
public clas StudentData {
  private List<integer> ages;
}

Now think that for some reason you need to use a third party library which do some complex calculation using ages of students. This is that third party class.
public class ComplexCalculator {
  public int doComplexCalculation(String csv) {
    int result = 0;
    String[] ages = csv.split(",");
    //do complex calculation using ages
    //result = .....
    return result;
  }
}

Look, unfortunately the input type accepted by above method is csv. If you need to use this method you need to convert the list of ages in to a csv string. What do you do now? Change your StudentData class to include the csv generation logic. No. There is a cleaner way. Just create an adapter class(ComplexCalculatorAdapter) and let it do that dirty mediation job for you.
public class ComplexCalculatorAdapter {
  public int callComplexCalculator(List<integer> ages) {

    String csv = null;
    //Logic to create csv string from list
    //String csv = .......
    return new ComplexCalculator().doComplexCalculation(csv);
  }
}
Now in your StudentData class you can call this adapter method as below.
int complexResult = new ComplexCalculatorAdapter().callComplexCalculator(ages);

That is all.
Note that by using Adapter Design Pattern you were able to accomplish the above task with minimal modifications to the existing code.

Thursday, November 27, 2014

Bridge Design Pattern - Simple tutorial with an example in Java

Bridge Design Pattern belongs to the Structural Design Patterns category.
As GOF says what you do by using this pattern is "Decouple an abstraction from its implementation so that the two can vary independently."

If I explain it further, in Bridge Design Pattern you decouple a functionality from a class hierarchy and create another interface and a class hierarchy which support that functionality and then create a bridge between these two hierarchies by creating a "has-a" relationship between two interfaces.

You will not understand this at once. But after carefully reading this lesson you will get a good understanding.

As usual Ill take our Vehicle interface to explain this pattern.
Assume that you have an interface called Vehicle which contains createVehicle() method.

public interface Vehicle {
    public void createVehicle();
}

Think that you need to have four types of vehicles. Those are Black Car, White Car, Back Motorbike and White Motorbike. So you will simply create below four classes which implements Vehicle interface.

public class BlackCar implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class WhiteCar implements Vehicle {
@Override
public void createVehicle() {
  installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class BlackMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

public class WhiteMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

You see that this is not the best design. For an example your paintInBlack() and paintInWhite() methods are duplicated. This design becomes more complex and less maintainable when the number of implementation classes are higher.
In this kind of situations Bridge Pattern comes to your help.
In Bridge Pattern what you do is create another interface(Painter) which does the painting job and then create another hierarchy of classes which implements this interface. Then you keep a reference to the Painter interface in Vehicle interface.
Now you have two class hierarchies which implement separate two interfaces. Having a reference to Painter interface in Vehicle interface is the bridge between these two hierarchies.
This is the Bridge Design Pattern.
With this pattern, your interfaces and implementation classes will be as below.

public abstract class Vehicle {
  protected Paint painter;
  public abstract void createVehicle();
}

public class Car extends Vehicle {
public Car(Paint painter) {
  this.painter = painter;
}

@Override
public void createVehicle() {
installCarParts();
  painter.paint();
}

private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class Motorbike extends Vehicle {
public Motorbike(Paint painter) {
this.painter = painter;
}

@Override
public void createVehicle() {
  installMotorbikeParts();
  painter.paint();
}

private void installMotorbikeParts() {
  System.out.println("Installing motorbike parts...");
}
}

public interface Paint {
  public void paint();
}

public class BlackPaint implements Paint {
@Override
public void paint() {
System.out.println("Painting in black...");
}
}

public class WhitePaint implements Paint {
@Override
public void paint() {
  System.out.println("Painting in white...");
}
}

In your client class now you can create various types of vehicles as below.
public class Test {
    public static void main(String[] args) {
Car whiteCar = new Car(new WhitePaint());
Car blackCar = new Car(new BlackPaint());
Motorbike whiteBike = new Motorbike(new WhitePaint());
Motorbike blackBike = new Motorbike(new WhitePaint());
    }
}

Saturday, November 22, 2014

Abstract Factory - Simple tutorial with an example in Java

    In Factory Method pattern we used a method called factory to create objects.

The concept of Abstract Factory Pattern is having a Factory Class which creates other factories according to the information given. If you remember the Factory Method tutorial you had a Vehicle interface and multiple classes which implement it. You had a factory called VehicleFactory which constructs the correct type of vehicle instance(car bus or van).
This pattern also belongs to the creational patterns group.

The difference in Abstract Factory Pattern is instead of having one VehicleFactory you have multiple factories such as WaterVehicleFactory and LandVehicleFactory ana there is another class which creates the correct factory for you.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below four classes implement above interface.

public class Bus implements Vehicle {
}
public class Car implements Vehicle {
}
public class Ship implements Vehicle {
}
public class Boat implements Vehicle {
}

We can categorize above four classes in to two groups, Land Vehicles and Sea Vehicles. So similarly we can have two factories to create them such as LandVehicleFactory and SeaVehicleFactory.
First we create an super abstract factory class or an interface (AbstractVehicleFactory) and extend LandVehicleFactory and SeaVehicleFactory classes from it as below.


public interface AbstractVehicleFactory {
public Vehicle getVehicle(String size);
}

public class LandVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if ("large".equals(size)) {
return new Bus();
} else {
return new Car();
}
}
}

public class SeaVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if("large".equals(size)) {
return new Ship();
} else {
return new Boat();
}
}
}

Finally you need a separate class which is responsible to create and return the correct factory according to the requirement.


public class FactoryCreator {
public static AbstractVehicleFactory getFactory(String terrainType) {
if("sea".equals(terrainType)) {
return new SeaVehicleFactory();
} else if("land".equals(terrainType)) {
return new LandVehicleFactory();
} else {
return null;
}
}
}

I think now you understand this pattern well. You can use below class to test it.


public class Test {
public static void main(String[] args) {
AbstractVehicleFactory factory = FactoryCreator.getFactory("sea");
Vehicle ship = factory.getVehicle("large");
System.out.println(ship.getClass().getSimpleName());
}
}

Thursday, November 20, 2014

Factory Method - Simple tutorial with an example in Java

Factory Method design pattern belongs to the creational design pattern group. Factory method is responsible of creating the correct object according to the information given.

For an example assume that you have an interface called Vehicle and multiple classes which implement it such as Bus, Car and Van. Then when you need to create an instance from one of above classes according to the passenger count, the factory method is responsible to construct and return the correct type of object.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below three classes implement above interface.
public class Bus implements Vehicle {
}

public class Car implements Vehicle {
}

public class Van implements Vehicle {
}

I put my factory method in a separate class so that other classes can use this method easily. This is my class which contains my factory method. When I call the getVehicle() method it returns me the correct type of object according to the passenger count I pass.

public class VehicleFactory {
public static Vehicle getVehicle(int passengerCount) {
if(passengerCount <= 4) {
return new Car();
} else if(passengerCount <= 18) {
return new Van();
} else {
return new Bus();
}
}
}

You can test this method as below.
public class Test {
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle(3);
Vehicle bus = VehicleFactory.getVehicle(25);

System.out.println(car.getClass().getSimpleName());
System.out.println(bus.getClass().getSimpleName());
}
}

Singleton Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The concept of this pattern is can be described as below.

"This pattern does not let creating more than one instance of a certain object."

It means you can use this pattern when you want to restrict other classes creating more than one instance of a certain class.
How can we do that.
Think that the name of your class which is needed to be singleton is MySingleton. You can make the class singleton as below.

public class MySingleton {
private static MySingleton mySingleton;

//Make the constructor private so that
//any body cant use this to create instances
private MySingleton() {
}

//Calling this method is the only way of creating an
//instance of this class. If there is no previously created
//instance this method creates an instance and returns
//that. Otherwise returns the previously created instance.
public static MySingleton getInstance() {
if(mySingleton == null) {
mySingleton = new MySingleton();
}
return mySingleton;
}
}

You can test this class as below.

public class Test {
public static void main(String[] args) {
MySingleton ms1 = MySingleton.getInstance();
MySingleton ms2 = MySingleton.getInstance();

System.out.println(ms1 == ms2);//returns true because two instance are the same
}
}

Wednesday, November 19, 2014

Prototype Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The core of this pattern can be described simply as below.

"If you want to construct multiple instances of an expensive object, just create one object and clone it multiple times."

✔  Create one instance of expensive object
✔  Clone it when you need another instance of that type
✔  Modify the properties of new(cloned) instance as required.

  Note that this pattern suits only if those instances should have nearly similar properties.
  It is not a must to use Object.clone() method to duplicate the object. You can write your own copy method to do this. To keep this lesson short in my Car class I implements the Cloneable interface and use Object.clone() method in CarCreator class.

Assume that you have a class called Car which can be used to build various types of cars. When using Prototype Pattern what you do is create a car initially and duplicate it when you need more cars.
See this example. This is the Car class.

public class Car implements Cloneable {
int doorCount = 0;

public Car() {
  // complex construction logic here
}

public int getDoorCount() {
return doorCount;
}

public void setDoorCount(int doorCount) {
this.doorCount = doorCount;
}

protected Object clone() {
try {
return super.clone();
} catch (Exception e) {
return null;
}
}

//..more lines here...
}

Ok. Now you should have another class(CarCreator) which is used when you need to create a new Car instance. At the very first time you call this class it goes through the expensive logic and creates an instance of Car object. As well this class keeps that instance for later use. When you request a new car instance at later time it clones the previously saved object and returns.

This is your CarCreator class.

public class CarCreator {
  private Car car;
  
  public Car createCar() {
    if(car == null) {
      car = new Car();//This construction is expensive
      return car;
    } else {
      //since we already have a car in hand we return a clone of that
      return (Car) car.clone();
    }
  }
}

Your client class to check above functionality would be as below.

public class Test implements Cloneable {
  CarCreator carCreator = new CarCreator();
  
  public static void main(String[] args) {
    Test test = new Test();
    //create a luxury car
    Car luxuryCar = test.createVehicle(4);
    //create a sports car
    Car sportsCar = test.createVehicle(2);
    
    System.out.println(luxuryCar.getDoorCount());
    System.out.println(sportsCar.getDoorCount());
  }
  
  private Car createVehicle(int doorCount) {
    Car vehicle = carCreator.createCar();
    vehicle.setDoorCount(doorCount);
    return vehicle;
  }
}

Builder Pattern - Simple tutorial with an example in Java

Builder design pattern belongs to the creational design pattern group. In Builder Pattern you arrange all the steps used to create an object in one separate class(Builder class).
Assume that you have a class or an interfaces called Vehicle. You can create various types of vehicles which are instances of this class(or interface). For an example an instance can be a car or a motorcycle.
Assume that the below class is your Vehicle class which contains complex methods.(Since I need to keep this tutorial short, I am not using an interface here. But note that the best design is making the vehicle class an interface and implementing the Car and Motorcycle classes using that.)

public class Vehicle {
  String name;
  public void addWheels(int count){}
  public void addController(){}
  public void addFuelTank(){}
  public void setName(String name){this.name = name;}
  public String getName(){return this.name;}
}

Building a car or a motorcycle is a complex and multi stepped process. In such cases you can use a VehicleBuilder to make this process organized. In a VehicleBuilder instance there is an instance of Vehicle class and getVehicle() method returns that after constructed.

This is your VehicleBuilder interface.

public interface VehicleBuilder {
  public void setWheels();
  public void setController();
  public void setFuelTank();
  public void setName();
  public Vehicle getVehicle();
}

You can have multiple implementations of this interface. For an example CarBuilder and MotorcycleBuilder.

public class CarBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 4 wheels (complex logic)
    vehicle.addWheels(4);
  }
  public void setController() {
    //Fix a steering wheel complex logic
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing car fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //seting name (complex logic)
    vehicle.setName("car");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

public class MotorcycleBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 2 wheels (complex logic)
    vehicle.addWheels(2);
  }
  public void setController() {
    //Fixing a handle (complex logic)
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing motorcycle fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //setting name (complex logic)
    vehicle.setName("Motorcycle");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

Now in your class you can use this builders to create cars or motorcycles as below.

public class Test {
  public static void main(String[] args) {
//Building a Car
    VehicleBuilder carBuilder = new CarBuilder();
    carBuilder.setName();
    carBuilder.setWheels();
    carBuilder.setController();
    carBuilder.setFuelTank();
    Vehicle car = carBuilder.getVehicle();
    System.out.println(car.getName());
    

//Building a Motorcycle
    VehicleBuilder motorcycleBuilder = new MotorcycleBuilder();
    motorcycleBuilder.setName();
    motorcycleBuilder.setWheels();
    motorcycleBuilder.setController();
    motorcycleBuilder.setFuelTank();
    Vehicle bike = motorcycleBuilder.getVehicle();
    System.out.println(bike.getName());
  }
}