Monday, June 25, 2012

Prototype Design Pattern

Introduction

Prototype design pattern is one of a creational design pattern. This pattern can be used when user wants to have an object but without instanciating it. That means using java clone feature. The advantage of this pattern is as you might know creating an object using new operator is very costly. But here we use clone method to create new objects. But you know if we want to create an object using clone method there should be existing object to make clone objects. So first object creation should be done by using the java new operator.

Example 

Suppose you want to draw some shapes. For example you want to draw shapes like Square, Triangle. But these drawing not only once. many times you want to draw Square and Triangle. In other words, you have to make instances of Square and Triangle classes. But you want to avoid that instance creation but make instances by cloning. So it is the prototype design pattern.

Following example code has Shape abstract class and Square and Triangle concrete classes. As you can see Shape class implement with Cloneable interface so that it can implement of cloning logic.

Shape.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public abstract class Shape implements Cloneable {

 public abstract void draw();
 
 @Override
 public Object clone() {
  Object clone = null;
  try {
   clone = super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return clone;
 }
 
}

Square.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Square extends Shape {

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

Triangle.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Triangle extends Shape {

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

Main.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Main {
 
 public static void main(String[] args) {
  Shape squareA = new Square();
  squareA.draw();
  Shape squareB = (Square) squareA.clone();
  squareB.draw();
  
  Shape triangleA = new Triangle();
  triangleA.draw();
  Shape triangleB = (Triangle) triangleA.clone();
  triangleB.draw();
 }

}

Wednesday, June 20, 2012

Builder Design Pattern

Introduction


Builder pattern is one of creational design pattern. It builds a complex object by building separated parts and finally integrates those parts and makes the complex object. But the construction logic is not visible to the user.

Example

Suppose you have to build a computer. But you also have to build computer parts such as processor, mother board, hard disk and RAM. So building all the parts finally integrate all the parts and build the final out put as computer (a desktop computer).  So this is the example I'm going to illustrate with java. Look at the following code and try to understand the concept of Builder design pattern of java.

Computer.java

package com.blog.patterns.builder;

/**
 * @author uditha
 */
public class Computer {

 private String processor;
 private String motherBoard;
 private String hardDisk;
 private String ram;

 public String getProcessor() {
  return processor;
 }

 public void setProcessor(String processor) {
  this.processor = processor;
 }

 public String getMotherBoard() {
  return motherBoard;
 }

 public void setMotherBoard(String motherBoard) {
  this.motherBoard = motherBoard;
 }

 public String getHardDisk() {
  return hardDisk;
 }

 public void setHardDisk(String hardDisk) {
  this.hardDisk = hardDisk;
 }

 public String getRam() {
  return ram;
 }

 public void setRam(String ram) {
  this.ram = ram;
 }
 
}

Builder.java

package com.blog.patterns.builder;

/**
 * @author uditha
 */
public interface Builder {

 public void buildProcessor();
 public void buildMotherBoard();
 public void buildHardDisk();
 public void buildRam();
 public Computer getComputer();
 
}

ComputerBuilder.java

package com.blog.patterns.builder;

/**
 * @author uditha
 */
public class ComputerBuilder implements Builder {
 
 private Computer computer;
 
 public ComputerBuilder() {
  computer = new Computer();
 }

 @Override
 public void buildProcessor() {
  computer.setProcessor("some processor");
 }

 @Override
 public void buildMotherBoard() {
  computer.setMotherBoard("some motherboard");
 }

 @Override
 public void buildHardDisk() {
  computer.setHardDisk("some hard disk");
 }

 @Override
 public void buildRam() {
  computer.setRam("some ram");
 }
 
 @Override
 public Computer getComputer() {
  return this.computer;
 }

}

Director.java

package com.blog.patterns.builder;

/**
 * @author uditha
 */
public class Director {
 
 public Computer buildComputer(Builder builder) {
  builder.buildProcessor();
  builder.buildMotherBoard();
  builder.buildHardDisk();
  builder.buildRam();
  return builder.getComputer();
 }

}

Main.java

package com.blog.patterns.builder;

/**
 * @author uditha
 */
public class Main {

 public static void main(String[] args) {
  Director director = new Director();
  Builder builder = new ComputerBuilder();
  Computer computer = director.buildComputer(builder);
  System.out.println(computer.getProcessor());
  System.out.println(computer.getMotherBoard());
  System.out.println(computer.getHardDisk());
  System.out.println(computer.getRam());
 }

}

Monday, June 18, 2012

Abstract Factory Pattern

Introduction


Abstract Factory Pattern can be defined as factory of factories. You can see the reason by looking at the example.

Example


Suppose you have 2 factories. Each factory makes phones and laptops. Suppose first factory is AppleFactory and other one is ToshibaFactory. AppleFactory makes IPhone and Mac laptop. ToshibaFactory makes ToshibaPhone and ToshibaLaptop. Let's see the code.

Phone.java


package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public abstract class Phone {

 public abstract String getCategory();
 
}

Laptop.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public abstract class Laptop {

 public abstract String getOperatingSystem();
 
}

Factory.java


package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public interface Factory {

 public Phone createPhone();
 public Laptop createLaptop();
 
}

IPhone.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class IPhone extends Phone {

 @Override
 public String getCategory() {
  return "Mobile Phone";
 }
 
}

Mac.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class Mac extends Laptop {

 @Override
 public String getOperatingSystem() {
  return "Mac";
 }

}

AppleFactory.java

package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class AppleFactory implements Factory {

 @Override
 public Phone createPhone() {
  return new IPhone();
 }

 @Override
 public Laptop createLaptop() {
  return new Mac();
 }

}

ToshibaPhone.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaPhone extends Phone {

 @Override
 public String getCategory() {
  return "Land Phone";
 }
 
}

ToshibaLaptop.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaLaptop extends Laptop {

 @Override
 public String getOperatingSystem() {
  return "Windows 7";
 }

}

ToshibaFactory.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaFactory implements Factory {

 @Override
 public Phone createPhone() {
  return new ToshibaPhone();
 }

 @Override
 public Laptop createLaptop() {
  return new ToshibaLaptop();
 }

}

Main.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class Main {

 public static void main(String[] args) {
  // apple factory
  Factory factory = new AppleFactory();
  Phone phone = factory.createPhone();
  Laptop laptop = factory.createLaptop();
  System.out.println(phone.getCategory());
  System.out.println(laptop.getOperatingSystem());
  
  // toshiba factory
  factory = new ToshibaFactory();
  phone = factory.createPhone();
  laptop = factory.createLaptop();
  System.out.println(phone.getCategory());
  System.out.println(laptop.getOperatingSystem());
 }

}

Monday, May 14, 2012

Factory Method Pattern


Introduction

Suppose we have a super class (abstract class or interface) and any number of sub classes. Based on some parameters we have to return an object of any sub class without knowing the logic inside. So in this case Factory Method Pattern can be used.

Example

By assuming you are familiar with the playing cards, I'm going to illustrate the example using playing cads. So you might know in the playing cards there are 4 kinds of kings. So lets create an interface name is King and 4 classes for 4 kinds of kings.  Lets assume passing some parameters ("C", "D", "H", "S") we want to get the suit of the object. Following are the created classes.

King.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public interface King {
 
 public String getSuit();

}

Club.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Club implements King {

 @Override
 public String getSuit() {
  return "Club";
 }

}

Diamond.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Diamond implements King {

 @Override
 public String getSuit() {
  return "Diamond";
 }
 
}

Heart.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Heart implements King {

 @Override
 public String getSuit() {
  return "Heart";
 }
 
}

Spade.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Spade implements King {

 @Override
 public String getSuit() {
  return "Spade";
 }
 
}

So far so good. Now we want the factory class, passing some parameter and get the instance of King. Following is the factory class.

Factory.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Factory {

 public King getKing(String key) {
  if ("C".equals(key)) {
   return new Club();
  } else if ("D".equals(key)) {
   return new Diamond();
  } else if ("H".equals(key)) {
   return new Heart();
  } else if ("S".equals(key)) {
   return new Spade();
  } else {
   throw new RuntimeException("No king found for the key : " + key);
  }
 }
 
}

If you wish to test this pattern I created a main class for you.

Main.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Factory factory = new Factory();
  King king = factory.getKing("C");
  System.out.println(king.getSuit());
  king = factory.getKing("D");
  System.out.println(king.getSuit());
  king = factory.getKing("H");
  System.out.println(king.getSuit());
  king = factory.getKing("S");
  System.out.println(king.getSuit());
  king = factory.getKing("K");
  System.out.println(king.getSuit());
 }

}

Friday, May 4, 2012

Singleton Pattern

Introduction

Singleton design pattern is the most simplest design pattern among all the other design patterns. This pattern gives you a single instance for you throughout the system or program.

Example

Suppose you have a class , say Singleton, and you want to have only one instance throughout your program. Is it clear? Just one instance. No more than one instance. So in this case you are aware to create only one instance throughout the program. Ok, in this case you have to use singleton design pattern. Let's see how it should be done.

Singleton.java

package com.blog.patterns.singleton;

/**
 * @author uditha
 */
public final class Singleton {

 private static final Singleton INSTANCE = new Singleton();
 
 private Singleton() {
  System.out.println("Singleton instance is created.");
 }
 
 public static Singleton getInstance() {
  return INSTANCE;
 }
 
 @Override
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException("Clone is prohibited.");
 }
 
}

Discussion

In this class you can see the constructor is private.
 private Singleton() {
  System.out.println("Singleton instance is created.");
 }
That means constructor is not visible to out side world. It is the tricky part of this pattern to prevent instance creation from out side the world. And another thing is you can see the field name INSTANCE is static and final.
 private static final Singleton INSTANCE = new Singleton();
As you already know static fields are created at class loading time and share the static fields with the instances created from its class. So that means static fields will never be created at the time it create instances. In this case the constructor is private. There is no way to create instances from out side the word. But you can see INSTANCE field was assigned a object of Singleton class. That means there is one instance of Singleton , created by itself. So making this field static, it will take care of sharing a single INSTANCE field with other instances of Singleton class (in any case). But according to above example it is not possible to create more than one instance.

Then next question is why this field is final. As you might know final fields can be assigned only once. So making that field final, guaranteed we use the same instance assigned at class loading time. In other words assigned object will not be changed.

If this field is private then how can access this INSTANCE variable from out side of this class. That is why we should provide a static method to access INSTANCE variable as follows.

 public static Singleton getInstance() {
  return INSTANCE;
 }

Advanced

  • You might have known about the java clone method of Object class. So using this method we can create a copy of any object. Why I mention this method because if we want to use singleton design pattern we should aware of creating clones of singleton class because we need only one object. So as a best practice we should use following code snippet to your class.

 @Override
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException("Clone is prohibited.");
 }

  • When creating a singleton class you should check about the thread safety of that class. Above example is thread safety one.
  • Next fact is avoiding sub classes. So you can do it this easily making the singleton class final.
  • Using == operator you can check getInstance()  method provide references that refers to same object or not.
package com.blog.patterns.singleton;

/**
 * @author uditha
 */
public class Main {
 
 public static void main(String[] args) {
  System.out.println("First instance creation begin");
  Singleton firstInstance = Singleton.getInstance();
  System.out.println("First instance creation end");
  System.out.println("Second instance creation begin");
  Singleton secondInstance = Singleton.getInstance();
  System.out.println("Second instance creation end");
  if (firstInstance == secondInstance) {
   System.out.println("Those instances refer to same object.");
  } else {
   System.out.println("Two different objects.");
  }
 }

}

Output
First instance creation begin
Singleton instance is created.
First instance creation end
Second instance creation begin
Second instance creation end
Those instances refer to same object.

Wednesday, April 25, 2012

Java Design Patterns

Simply design pattern is a solution for the common software problem. Design patterns can be categorized into 3 sections.
  • Creational design patterns
  • Structural design patterns
  • Behavioral design patterns
Lets discuss those topics one by one.

Creational Design Patterns

As the name of  creational design patterns create objects (instantiate) and give it to the user. But the way of creating object or instantiating object, the logic of creating object, is hidden from the user. In other words encapsulated. Followings are creational design patterns.


Structural Design Patterns

Structural design patterns describe how classes relate or combine with each other. Followings are the structural design patters.
  • Adapter pattern
  • Composite pattern
  • Proxy pattern
  • Flyweight pattern
  • Facade pattern
  • Bridge pattern
  • Decorator pattern

Behavioral Design Patterns

Behavioral design patterns are describe the way of objects interact with each other. Followings are the behavioral design patterns.
  • Template pattern
  • Mediator pattern
  • Chain of responsibility pattern
  • Observer pattern
  • Strategy pattern
  • Command pattern
  • State pattern
  • Visitor pattern
  • Iterator pattern
  • Momento pattern