Posts Tagged ‘Design Paterns’

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();

    }
}

Configuration files and ConnectionStrings

Monday, January 5th, 2009

One of the first things I’ve learned as .NET developer was using of App.config or Web.config files. Almost every application in which development I took a part had some database. Here is the brief sample how to connect to SQL Server from C#:

			string connString = @"Server=(LOCAL);Database=Northwind;User ID=sa;Password=;";
			string sqlString =  "SELECT * FROM PRODUCTS";
			DataSet ds = new DataSet();
			SqlConnection conn = new SqlConnection(connString);
			conn.Open();
			SqlDataAdapter da = new SqlDataAdapter(sqlString, conn);

			da.Fill(ds);
			dgrProducts.DataSource = ds;
			dgrProducts.DataBind();
			conn.Close();

This code will open connection to database, read table and fill data set. Then we bind data from data set to dataGrid or GridView (control named dgrProducts).
But it is not a good practice to keep connection string hard coded. Place it into configuration file.

< ?xml version="1.0" encoding="utf-8" ?>

	
	
		
	

and here is how you can read value from configuration file. It is a good practice to create new project, type of Class Library for that.

using System;
using System.Configuration;

namespace ConnectionString
{
	public class Configuration
	{
		public static string ReadConnectionString
		{
			get
			{
				return ConfigurationSettings.AppSettings.Get("ConnectionString");
			}
		}
	}
}

this sample runs on .NET 1.1 framework
For 3.0 .NET we use:

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace ConnectionString
{
    public class Configuration
    {
        protected static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ConnectionString"].
                    ToString();
            }
        }
    }
}

As you can see we use System.Configuration reference.

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
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in