Archive for the ‘Design Paterns’ Category

Design Pattern - Adapter

Thursday, January 15th, 2009

In all my previous posts I wrote about Creational Design Patterns: Singleton, Abstract Factory, Factory method, Prototype and Builder. In this posts I will introduce you with: Adapter - Structural Pattern.
Definition of “Adapter” says:
Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces, so it converts the interface of a class into another interface clients expect. Here is UML diagram

design pattern - adapter

design pattern - adapter


Here is the Java code which demonstrates using of Adapter pattern. This is abstract class Shape. I use it to define some very simple interface.

abstract class Shape {
	public abstract double GetVolume();
}

and now I create 2 clases which implements this interface

public class Square extends Shape {

	private int radius;

	public Square(int r)
	{
		radius = r;
	}

	public double GetVolume()
	{
		return radius * radius;
	}
}
public class Triangle extends Shape {

	private int a;

	public Triangle(int x)
	{
		a = x;
	}

	public double GetVolume()
	{
		return (a * a * Math.sqrt(3)) /4;
	}
}

and what if we have one more class but with the wrong interface (functionality is ok, but interface not)

public class XCircle {

	private int radius;

	public XCircle(int r)
	{
		radius = r;
	}

	public double XGetVolume()
	{
		return radius * radius * Math.PI;
	}
}

but we need Cirlce class. Here is what we do than:

public class Circle extends Shape {

	private int radius;
	private XCircle circle;
	public Circle(int r)
	{
		radius = r;
		circle = new XCircle(radius);
	}

	public double GetVolume()
	{
		return circle.XGetVolume();
	}
}

at the end here is simple client application to demonstrate how it works:

public class Circle extends Shape {

	private int radius;
	private XCircle circle;
	public Circle(int r)
	{
		radius = r;
		circle = new XCircle(radius);
	}

	public double GetVolume()
	{
		return circle.XGetVolume();
	}
}

that is all :)

Design Patterns: Prototype

Saturday, January 10th, 2009

Prototype pattern: used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.
    Here is UML diagram for Prototype pattern.
    Design Patterns - Prototype

    Design Patterns - Prototype


    Here is the code examples:

    /**
     * The Animal abstract class is the prototype in the "Prototype" Pattern. The
     * animal class contains properties that describe on a abstract level the different
     * prototypes that can exist in the pattern example.
     */
    public abstract class Animal implements Cloneable {
    	protected int numberOfLegs = 0;
    	protected String description = "";
    	protected String name = "";
    	public abstract String helloAnimal();	
    
    	/**
    	 * The clone method creates a clone of the current Animal object.
    	 */
    	public Animal clone() {
    		Animal clonedAnimal = null;
    		try {
    			clonedAnimal = (Animal) super.clone();
    			clonedAnimal.setDescription(description);
    			clonedAnimal.setNumberOfLegs(numberOfLegs);
    			clonedAnimal.setName(name);
    
    		} catch (CloneNotSupportedException e) {
    			e.printStackTrace();
    		}
    		return clonedAnimal;
    	}  
    
    	public String getDescription() {
    		return description;
    	}
    
    	public void setDescription(String description) {
    		this.description = description;
    	}
    
    	public int getNumberOfLegs() {
    		return numberOfLegs;
    	}
    
    	public void setNumberOfLegs(int numberOfLegs) {
    		this.numberOfLegs = numberOfLegs;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    }
    
    /**
     * The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator
     * class contains two concrete prototypes that is initialized during the initialization of
     * the class. The AnimalCreator class forms part of the "Prototype" pattern by returning
     * a cloned object (Animal) to the client, withou the client knowing the type of the prototype.
     */
    public class AnimalCreator {
    
    	private Animal sheep = new Sheep();	
    
    	private Animal chicken = new Chicken();
    
    	public AnimalCreator() {
    		sheep.setName("Sheep");
    		sheep.setNumberOfLegs(4);
    		sheep.setDescription("Four legged creature that makes wool.");
    
    		chicken.setName("Chicken");
    		chicken.setNumberOfLegs(2);
    		chicken.setDescription("Two legged creature that crosses roads.");
    	} 
    
    	public Animal retrieveAnimal(String kindOfAnimal) {
    		if ("Chicken".equals(kindOfAnimal)) {
    			return (Animal) chicken.clone();
    		} else if ("Sheep".equals(kindOfAnimal)) {
    			return (Animal) sheep.clone();
    		} // if
    
    		return null;
    	} // method retrieveAnimal
    }
    
    public class Chicken extends Animal {
    	private int numberOfClones = 0;
    	public String helloAnimal() {
    	StringBuffer chickenTalk = new StringBuffer();
    	chickenTalk.append("Cluck cluck World. I am ");
    	chickenTalk.append(name);
    	chickenTalk.append(". I have ");
    	chickenTalk.append(numberOfLegs);
    	chickenTalk.append(" legs.");
    	return chickenTalk.toString();
    	} // helloAnimal
    
    	public Chicken clone() {
    		Chicken clonedChicken = (Chicken) super.clone();
    		String chickenName = clonedChicken.getName();
    		numberOfClones++;
    		clonedChicken.setName(chickenName + numberOfClones);
    		return clonedChicken;
    	} // method clone
    }
    
    public class Sheep extends Animal {
    	private int numberOfClones = 0;
    	public String helloAnimal() {
    	StringBuffer sheepTalk = new StringBuffer();
    	sheepTalk.append("Meeeeeee World. I am ");
    	sheepTalk.append(name);
    	sheepTalk.append(". I have ");
    	sheepTalk.append(numberOfLegs);
    	sheepTalk.append(" legs.");
    	return sheepTalk.toString();
    	}
    
    	public Sheep clone() {
    		Sheep clonedSheep = (Sheep) super.clone();
    		String sheepName = clonedSheep.getName();
    		numberOfClones++;
    		clonedSheep.setName(sheepName + numberOfClones);
    		return clonedSheep;
    	} 
    
    }
    

    and for the end client class

    public class AnimalClient {
    	public static void main(String[] args) {
    		AnimalCreator animalCreator = new AnimalCreator();
    		Animal[] animalFarm = new Animal[8];
    		animalFarm[0] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[1] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[2] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[3] = animalCreator.retrieveAnimal("Chicken");
    
    		animalFarm[4] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[5] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[6] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[7] = animalCreator.retrieveAnimal("Sheep");
    
    		for (int i= 0; i< =7; i++) {
    			System.out.println(animalFarm[i].helloAnimal());
    		} // for
    	}
    }
    

Design Patterns: Builder

Friday, January 9th, 2009

In software engineering, creational design patterns are design patterns that we’re using in object creation. Creational design patterns solve this problem by somehow controlling this object creation.

Here is the list of creational design patterns:

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

Now let’s get back to Builder pattern.
here is UML

Design pattern - Builder

Design pattern - Builder


The intention of Builder Pattern is to abstract steps of construction of object so that different implementations of these steps can construct different representations of objects.
Often, the Builder Pattern is used to build Products in accordance to the Composite pattern, a structure pattern.
Example

public class Director
{
  // Builder uses a complex series of steps
  public void Construct(VehicleBuilder vehicleBuilder)
  {
    vehicleBuilder.BuildFrame();
    vehicleBuilder.BuildEngine();
    vehicleBuilder.BuildWheels();
    vehicleBuilder.BuildDoors();
  }
}
public abstract class VehicleBuilder {
    protected Vehicle vehicle;
    // Property
    public Vehicle getVehicle()
    {
    	return vehicle;
    }

    public abstract void BuildFrame();
    public abstract void BuildEngine();
    public abstract void BuildWheels();
    public abstract void BuildDoors();
}
public class ScooterBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("Scooter");
      vehicle.AddObject("frame", "Scooter Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "50 cc");
    }

    public void BuildWheels()
    {
      vehicle.AddObject("wheels", "2");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "0");
    }
}
public class MotorCycleBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("MotorCycle");
      vehicle.AddObject("frame", "MotorCycle Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "500 cc");
    }

    public void BuildWheels()
    {
      vehicle.AddObject("wheels", "2");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "0");
    }
}
public class CarBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("Car");
      vehicle.AddObject("frame", "Car Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "2500 cc");
    }

    public  void BuildWheels()
    {
      vehicle.AddObject("wheels", "4");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "4");
    }
}
import java.util.*;

//"Product"
public class Vehicle {
	 private String type;
	    private Hashtable parts = new Hashtable();

	    // Constructor
	    public Vehicle(String type)
	    {
	      this.type = type;
	    }

	    public void AddObject(String key, String value)
	    {
	    	parts.put(key, value);
	    }

	    public String GetObject(String key)
	    {
	    	return parts.get(key);
	    }	    

	    public void Show()
	    {
	      System.out.println("\n---------------------------");
	      System.out.println("Vehicle Type: " + type);
	      System.out.println(" Frame : " + parts.get("frame"));
	      System.out.println(" Engine : " + parts.get("engine"));
	      System.out.println(" #Wheels: " + parts.get("wheels"));
	      System.out.println(" #Doors : " + parts.get("doors"));
	    }
}

and for the end, here is the client to show how all of this works together!

public class Client {

    public static void main(String[] args)
    {
      // Create shop with vehicle builders
      Director director = new Director();
      VehicleBuilder b1 = new ScooterBuilder();
      VehicleBuilder b2 = new CarBuilder();
      VehicleBuilder b3 = new MotorCycleBuilder();

      // Construct and display vehicles
      director.Construct(b1);
      b1.getVehicle().Show();

      director.Construct(b2);
      b2.getVehicle().Show();

      director.Construct(b3);
      b3.getVehicle().Show();

    }
}

Design Pattern - Factory Method

Sunday, October 26th, 2008

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

uml diagram

The classes and/or objects participating in this pattern are:

  • Product (Page)
      defines the interface of objects the factory method creates
  • ConcreteProduct (SkillsPage, EducationPage, ExperiencePage)
      implements the Product interface
  • Creator (Document)
      declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
      may call the factory method to create a Product object.
  • ConcreteCreator (Report, Resume)
      overrides the factory method to return an instance of a ConcreteProduct.

code:

// “Product”

abstract class Page
  {
  }

“ConcreteProduct”

class SkillsPage extends Page
  {
  }

“ConcreteProduct”

class EducationPage extends Page
  {
  }

“ConcreteProduct”

class ExperiencePage extends Page
  {
  }

“ConcreteProduct”

class IntroductionPage extends Page
  {
  }

“ConcreteProduct”

class ResultsPage extends Page
  {
  }

“ConcreteProduct”

class ConclusionPage extends Page
  {
  }

“ConcreteProduct”

class SummaryPage extends Page
  {
  }

“ConcreteProduct”

class BibliographyPage extends Page
  {
  }

“Creator”

import java.util.*;

public abstract class Document {
    private ArrayList pages = new ArrayList();

    // Constructor calls abstract Factory method
    public Document()
    {
      this.CreatePages();
    }

    public ArrayList GetPages()
    {
      return this.pages;
    }
    public void AddPages(Page page)
    {
      this.pages.add(page);
    }    

    // Factory Method
    public abstract void CreatePages();

}

“ConcreteCreator”

public class Resume extends Document {

    // Factory Method implementation
    public void CreatePages()
    {
    	AddPages(new IntroductionPage());
    	AddPages(new ResultsPage());
    	AddPages(new ConclusionPage());
    	AddPages(new SummaryPage());
    	AddPages(new BibliographyPage());
    }
}

“ConcreteCreator”

public class Report extends Document {

    // Factory Method implementation
    public void CreatePages()
    {
    	AddPages(new SkillsPage());
    	AddPages(new EducationPage());
    	AddPages(new ExperiencePage());
    }
}

and here goes client which use all of this above:

public class Client {

	public static void main(String[] args)
	{
	      // Note: constructors call Factory Method
	      Document[] documents = new Document[2];
	      documents[0] = new Resume();
	      documents[1] = new Report();

	      // Display document pages
	      for (Document document : documents)
	      {
	        System.out.println("\n" + document.getClass().getName() + "--");
	        for (Page page : document.GetPages())
	        {
	          System.out.println(" " + page.getClass().getName());
	        }
	      }

	}
}

this is program output:

Resume ——-
SkillsPage
EducationPage
ExperiencePage
Report ——-
IntroductionPage
ResultsPage
ConclusionPage
SummaryPage
BibliographyPage

Design Pattern - Abstract Factory

Tuesday, October 7th, 2008

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
uml diagram

code:

“AbstractFactory” class

public abstract class ContinentFactory
{
	public abstract Herbivore CreateHerbivore();
	public abstract Carnivore CreateCarnivore();
}

“ConcreteFactory1″

public class AfricaFactory extends ContinentFactory
  {
    public Herbivore CreateHerbivore()
    {
      return new Wildebeest();
    }
    public Carnivore CreateCarnivore()
    {
      return new Lion();
    }
  }

“ConcreteFactory2″

public class AmericaFactory extends ContinentFactory
  {
    public Herbivore CreateHerbivore()
    {
      return new Bison();
    }
    public Carnivore CreateCarnivore()
    {
      return new Wolf();
    }
  }

“AbstractProductA”

public abstract class Herbivore {

}

“AbstractProductB”

public abstract class Carnivore {
	 public abstract void Eat(Herbivore h);
}

“ProductA1″

public class Wildebeest extends Herbivore {

}

“ProductB1″

public class Lion extends Carnivore {
	public void Eat(Herbivore h)
    {
      // Eat Wildebeest
      System.out.println(this.getClass().toString()+
        " eats " + h.getClass().toString());
    }
}

“ProductA2″

public class Bison extends Herbivore  {

}

“ProductB2″

public class Wolf extends Carnivore {
	public void Eat(Herbivore h)
    {
      // Eat Wildebeest
      System.out.println(this.getClass().toString()+
        " eats " + h.getClass().toString());
    }
}
public class AnimalWorld {

    private Herbivore herbivore;
    private Carnivore carnivore;

    // Constructor
    public AnimalWorld(ContinentFactory factory)
    {
      carnivore = factory.CreateCarnivore();
      herbivore = factory.CreateHerbivore();
    }

    public void RunFoodChain()
    {
      carnivore.Eat(herbivore);
    }

 }

What is the point? Well our AnimalWorld class works wit abstract classes. If we need to add new herbivore or carnivore it is not a problem. We will create new class which extends Herbivore or Carnivore class. Also if we need some other Continental factory, the AnimalWorld class will work fine.

and now let’s take a look of client code:

public class Client {

	public static void main(String[] args){

	      // Create and run the Africa animal world
	      ContinentFactory africa = new AfricaFactory();
	      AnimalWorld world = new AnimalWorld(africa);
	      world.RunFoodChain();

	      // Create and run the America animal world
	      ContinentFactory america = new AmericaFactory();
	      world = new AnimalWorld(america);
	      world.RunFoodChain();	     

	}
}



After you start Client here is the output:

Output:
Lion eats Wildebeest
Wolf eats Bison

Design Pattern - Singleton

Wednesday, September 17th, 2008

The Singleton Pattern is quite simply a design pattern that allows only one instance of itself to be created per application pool or application instance and provides one point of access to the single unique instance.

Ensure a class only has one instance, and provide a global point of access to it.

public class Singleton {

	protected Singleton() { }

	private static Singleton _instance = null;
	/**
	 * @return The unique instance to this class.
	 */
	public static Singleton getInstance() {
		if(null == _instance) {
			_instance = new Singleton();
		}
		return _instance;
	}
}



As you can see the idea is not to use public constructor. With protected or private constructor in some other class we can not do something like this:

Singleton objSingleton = new Singleton();

The other idea is to use static method getInstance();

this is how it works in some test client:

public class TestSingleton() {
    public static void main(string[] args) {
        Singleton objSingleton;
        objSingleton.getInstance();
    }
}
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in