Sep 082011
 

Go around and look for some method to remember Design Pattern, I saw a site summarize each Design Pattern with a line like this:

  • Abstract Factory: Creates an instance of several families of classes
  • Prototype: A fully initialized instance to be copied or cloned
  • Singleton: A class in which only a single instance can exist

But how can you remember it all? I cannot imagine that I can recall “Abstract Factory” is “Creates an instance of several families of classes” at all.

Design Pattern is so abstract and so hard to remember, so each time I write an entry about Design Pattern I do my best to put an easy to remember example. I believe the real life examples will be easier to understand and remember than the descriptions and principles.

Now let’s me summarize some Design Patterns by using Images of real life example.

 Singleton Pattern
searchdaily net java singleton design pattern thumb Remember Design Patterns by Images singleton pattern example images thumb Remember Design Patterns by Images

 

It’s the pattern of single service but multiple user like: there’s one receptionist at a hotel and there are multiple visitors. There is one President in a country and million citizens to manage

 Abstract Factory Pattern

Just think of the abstract Vehicle Factory that ferrari vs audi r8 thumb Remember Design Patterns by Imagescan produce any cars. And there are real Vehicle Factory like one is based in Germany (Audi and Mercedes) or factory is based in Italy like Ferrari and Iveco.

The same type of  products are created by different factories give different result in the end.

Factory Method Pattern

image thumb7 Remember Design Patterns by ImagesThe Factory method is much like Abstract Factory: to create different objects. But the difference is that Factory Method is not based on the different Factories but to base on different Parameters passed to the creator.

Take the calculator for example, base on the type of calculator we select, the different calculators will be created

 

Chain of Responsibility Pattern

The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver, by giving more than one object a chance to handle the request. Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.

chain of responsibility pattern thumb Remember Design Patterns by Images

Continue reading »

Aug 212011
 

Long time ago I’ve introduced how to copy data from one object to another using Java Reflection technology. But it’s not a way of creating new object like Prototype. Prototype is a Creational Pattern for “making dynamic creation easier by defining classes whose objects can create duplicates of themselves.”

java prototype clone thumb Prototype Design Pattern Tutorial

Let me give an example of Robot Cloning. Maybe you’ve seen this in some Doraemon cartoon where Nobita doesn’t have much toys like Suneo and he asked Doraemon to clone the toys for him.

Now let’s see how could Doraemon’s Cloning Mirror do this wlEmoticon smilewithtongueout5 Prototype Design Pattern Tutorial 

Suneo is rich and he has many toys including the SuneoRobot which Nobita likes to own one, but the Nobi is poor, they don’t have money for this. Luckily, SuneoRobot accidently implements the Cloneable interface of java.lang

package net.searchdaily.java.design.pattern.prototype;

/**
 * Prototype Design Pattern by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class SuneoRobot implements Cloneable {
	private String normalWeapon;
	private String superWeapon = "";
	private boolean flyingMode;

	public SuneoRobot() {
		this.normalWeapon = "Normal Weapon Activated";
		this.flyingMode = false;
	}

	public void sayHello() {
		System.out.println("Hello, I'm a SuneoRobot");
		System.out.println("I have Normal Weapon always activated");
		if (!"".equals(this.superWeapon)) {
			System.out.println("and I have Super Weapon activated too");
		}
		if (flyingMode) {
			System.out.println("Yet I can fly icon smile Prototype Design Pattern Tutorial ");
		}
	}

	@Override
	protected SuneoRobot clone() throws CloneNotSupportedException {
		return new SuneoRobot();
	}

	public void activateSuperRobotMode() {
		this.flyingMode = true;
		this.superWeapon = "Super Weapon Activated";
	}

	public String getNormalWeapon() {
		return normalWeapon;
	}

	public void setNormalWeapon(String normalWeapon) {
		this.normalWeapon = normalWeapon;
	}

	public String getSuperWeapon() {
		return superWeapon;
	}

	public void setSuperWeapon(String superWeapon) {
		this.superWeapon = superWeapon;
	}

	public boolean isFlyingMode() {
		return flyingMode;
	}

	public void setFlyingMode(boolean flyingMode) {
		this.flyingMode = flyingMode;
	}

}

That’s the Robot of Suneo, And here is the secret weapon of Doraemon – the Cloning Mirror:

Continue reading »

Aug 202011
 

Builder is one of the Creational Pattern to simplify the process of creating an object by defining a class – The Builder – whose purpose is to build object of other class.java design pattern builder make car toy thumb Builder Design Pattern Tutorial

Let me give an example by building a simple toy car as above. When building a car like above, you don’t have to build all from scratch but to build from wheels and body that are already built. So the car construction will have some steps like: wheels construction, body construction…This is also said in the book Design Pattern of GoF: “Separate the construction of a complex object from its representation so that the same construction process can create different representations

OK, now let’s get started by defining Car Parts: Car Body and Car Wheels

package net.searchdaily.java.design.pattern.builder;

/**
 * Builder Design Pattern by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class CarBody {
	private String name;

	public CarBody(String name) {
		this.name = name;
		System.out.println(name + " is Created");
	}

	public String getName() {
		return name;
	}
}
package net.searchdaily.java.design.pattern.builder;

/**
 * Builder Design Pattern by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class CarWheels {
	private String name;

	public CarWheels(String name) {
		this.name = name;
		System.out.println(name + " is Created");
	}

	public String getName() {
		return name;
	}
}

Next we will define the CarTemplate that contain the specification of a ToyCar

Continue reading »

Aug 062011
 

My today’s article about Java is Factory Method pattern.

What is Factory Method?

Well in one word you can call it the “Virtual Constructor” method. And for the long description it is the way to create object (constructor) but the kind of object to be created is left to subclasses to decide.

When to use Factory Method?
  • You want to create an extensible framework. This mean you allow some decisions especially for what kind of object to be created can extend and decide later.
  • You want a subclass rather than its superclass to decide what kind of an object to create.
  • You know when to create an object, but not what kind of an object.
  • You want to parameterize the constructor or the getObject() method so that base on different parameters passed the result objects are different too.
Factory Method Example

Let’s me give example by using the Calculator application built in most Windows, you can select various Calculator from Basic to Scientific to Programmer Calculator.

factory method thumb Factory Method pattern tutorial

With the above example: Suppose that ScientificCalculator, BasicCalculator and ProgrammerCalculator are all extended the Calculator (base class).

Continue reading »

Jul 262011
 

After my recent post about a Concrete Factory method: Singleton I decide to write more about object creational pattern in Java, and here it goes the Abstract Factory…

What is Abstract Factory ?

Abstract Factory is a method of creating families of objects (products) without having to specify their concrete classes (concrete factory) – maybe that’s why the name is Abstract Factory.

searchdaily net java design pattern Abstract Factory example 1 thumb Abstract Factory design pattern tutorial

When to use Abstract Factory ?

  • When how the object is created should be transparent to the client.
  • When the application need the object should be configured with one of multiple families of the products.
  • When you want to provide a set of objects that have relationships and the contracts revealed but not the implementations.

 

How to implement Abstract Factory pattern ?

  1. Abstract Factory: you will have to write a class or just an interface to define the creation methods for the abstract products.
  2. Abstract Product: you will write a class or an interface that describe how the product will be and how the product will be used by other application.
  3. Concrete Factory: a subclass of the Abstract Factory, this is the class where you implement the creation of the products.
  4. Concrete Product: a subclass of the Abstract Product, this is the class where you implement the specification of the what and how given by the abstract product.

Example

in this tutorial, I’d like to write about Vehicle Factory where makes car and truck. I will make different factories for Germany (Audi and Mercedes-Benz) and Italy (Ferrari and Iveco)

Continue reading »

Jul 212011
 

What is Singleton?

Singleton is one of well-known design pattern invented to allow only one instance object being created from a specific class but it will be shared between other processes that use the object. searchdaily net java singleton design pattern thumb Singleton pattern tutorial

When should I use Singleton?

The answer is vary but depend on your need to decide between using Singleton or not. Here I give you some example where they often use Singleton:

  • Application always need a single log file or log console so that logging can be written from every objects/processes that are running, in this case they use Singleton for the log object.
  • Singleton is used in managing database connections. Why? because the number of database connections are a limited and shared resource. It cannot serve more than what it has but the need is often higher than availability so it need to be shared. With one connection manager we can manage to share these db connections between those who need.
  • File manager, print spooler, framework configuration file.. are the same as database connections as I mentioned above so the same technique will be applied.

How to create Singleton pattern?

  1. Make private all constructor even the default constructor because we will not allow object creation from the outside.
  2. Create a private static instance of the class. This is the only object of the class that will return to the caller.
  3. Because the instance is static then finally we will create a synchronized static method that return the instance. Continue reading »