Aug 242011
 

What will you do if you want to add more features to an existing class without changing it? The simplest answer would be to extends it, another good answer for this is to do like what the Composite Pattern does – to make a wrapper of the class. But for a better answer, we should use both of them with the Decorator Pattern.

What is Decorator Pattern?

To make it simple: the Decorator Pattern is one of the Structural Patterns that utilizes the combination of Extending and Wrapping a class in a standard way to add more features to a component.

And for an in-depth design, please see the example below:

decorator pattern example thumb Use Decorator Pattern to Enhance your Component

As you can see in the picture, there are three famous Text Editor that everybody knows: Notepad, Notepad++ and Word.

  • Notepad is the simplest text editor, it can create new text file and save them, everything is in plain-text only.
  • Notepad++ supports user by giving format various type of text file: .java, .php, .html (with color and folding), and it can save file with various file format too.
  • And finally Word is the biggest text editor here, with it you can edit and publish press: RichText format, picture, table, calculation and more are supported, save file in .DOC and .HTML and more if you need to.

That’s for the story about three characters we will use in the demonstration.

Decorator Pattern Example

First let’s see how we will define a standard for Notepad or Notepad++ or Word or whatever text editor must conform to: The TextEditor interface.

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

/**
 * Decorator Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public interface TextEditor {
	public String create(); // create text file

	public String edit(); // edit the file

	public String save(); // save the change to hard disk
}

And now we will create a decorator which wrapped the TextEditor to enhance it feature and also implements TextEditor interface to conform standard.

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

/**
 * Decorator Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public abstract class TextEditorDecorator implements TextEditor {
	protected TextEditor enhancedTextEditor; // will support more features later

	public TextEditorDecorator(TextEditor textEditor) {
		this.enhancedTextEditor = textEditor;
	}

	@Override
	public String create() {
		return this.enhancedTextEditor.create();
	}

	@Override
	public String edit() {
		return this.enhancedTextEditor.edit();
	}

	@Override
	public String save() {
		return this.enhancedTextEditor.save();
	}

}

Basic function like create(), edit() or save() we will ask the basic TextEditor to do it wlEmoticon smile31 Use Decorator Pattern to Enhance your Component

Continue reading »

Aug 222011
 

Have you read or watch the anime named: Voltron: Defender of the Universe? That’s one good example of the Composite Design Pattern.

voltron composite design pattern thumb Composite Design Pattern Tutorial

As you can see there are 5 Lions combined to form Voltron for a greater power to defend the Universe. wlEmoticon openmouthedsmile3 Composite Design Pattern Tutorial That’s for the story and here is how we map it to technical definition:

“The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly” (From wiki)

When to use Composite Design Pattern?
  • When there is a component model with a branch-leaf structure (whole-part or container-contained).
  • When the structure can have any level of complexity, and is dynamic.
  • When you want to treat the component structure uniformly, using common operations throughout the hierarchy.
Composite Pattern Example

That’s quite long for the introduction, let’s me show you the example of the Voltron Super Robot wlEmoticon smile29 Composite Design Pattern Tutorial

Suppose that all Robots have names and they can fire() (with electric or laser I guess)

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

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public abstract class Robot {
	protected String name;

	/**
	 * Fire function.
	 * 
	 * @return true if fire successful, false if weapon error.
	 */
	abstract protected boolean fire();
}

The LionRobot is-a Robot which has its own firing capability.

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

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class LionRobot extends Robot {
	public LionRobot(String name) {
		this.name = name;
	}

	@Override
	protected boolean fire() {
		System.out.println(name + " is shooting ");
		return true;
	}

}

Next is the VoltronRobot class:

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

import java.util.ArrayList;
import java.util.List;

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class VoltronRobot extends Robot {
	List fiveLions;

	public VoltronRobot() {
		fiveLions = new ArrayList();
	}

	public void add(LionRobot lion) {
		if (null == fiveLions) {
			fiveLions = new ArrayList();
		}

		fiveLions.add(lion);
	}

	public void remove(LionRobot lion) {
		if (null != fiveLions && fiveLions.contains(lion)) {
			fiveLions.remove(lion);
		}
	}

	@Override
	protected boolean fire() {
		if (null != fiveLions && fiveLions.size() == 5) {
			for (LionRobot lion : fiveLions) {
				lion.fire();
			}
			System.out.println("SUPER LIONS POWER COMBINED FIRE AT ONCE");
		} else {
			System.out.println("Err...Voltron didn't collect enough Lions.");
		}
		return false;
	}

}

You can see that Voltron Robot has a list of list of Lions, and the Five Lions will be integrated into him later (composite). So for it easier to integrate, The Voltron Robot has the power to add() a lion to him or remove() it away.

Continue reading »

Aug 212011
 

Adapter Pattern maybe simple to get the concept because you will see it everyday. Technically an Adapter can be described as a device to helps two incompatible devices to work together. And for Software Engineer guys like me I would describe it as an interfaceto act as an intermediary between two classes, converting the interface of one class so that it can be used with the other

space shuttle rocket separation thumb Adapter Design Pattern TutorialThere are two way of implementing the Adapter Pattern: one uses Composite Method and the other uses Inheritance.

I will show the Composite way of Adapter Pattern first.

Let’s say we have a Space Shuttle which will use two Rockets for lifting them out of the Earth’s gravity. If we have a couple of Two Rockets, of course they can fly.

So if the Space Shuttle cannot fly by itself, but if a Space Shuttle equipped with the Two Rockets power, it can also fly away. But the equipping process must ask for the help of a Rocket Adapter. That’s for the story, let see how we will implement them using Java:

First we will define the TwoRockets and their flying power wlEmoticon smilewithtongueout6 Adapter Design Pattern Tutorial

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

/**
 * Adapter Design Pattern by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class TwoRockets {
	public String flyPower(String connectPoint1, String connectPoint2) {
		return "TwoRockets: We're flying with " + connectPoint1 + " and " + connectPoint2;
	}
}

Then we define the Adapter who will convert the fly power of the TwoRockets to the SpaceShuttle using the connectors.

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

/**
 * Adapter Design Pattern by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class RocketAdapter {
	private TwoRockets twoRockets;

	public String convertFlyPower(String shuttleConnector1,
			String shuttleConnector2) {
		twoRockets = new TwoRockets();
		// Two rockets will now fly with the Shuttle's fuel
		return twoRockets.flyPower(shuttleConnector1, shuttleConnector2); // Conversion of power
	}
}

Now let’s see how the Space Shuttle use Rocket Adapter to fly:

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 »