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 272011
 
What is Proxy Pattern?

Proxy is one of famous structural design pattern to “provide a surrogate or placeholder for another object to control access to it” (G.o.F).

image thumb96 Proxy Pattern tutorial and RMI example

In this diagram, you can see that Client want to doSomething() by the RealSubject. But we don’t want Client to interact with ReadSubject directly. Maybe there’s security reason or RealSubject is very costly, we can not deliver it to each Client. Instead we provide a proxy to each client, and when the client request to doSomething(), the RealSubject will do then.

When to use Proxy Pattern?

You use Proxy Pattern when you want to provide a representative of another object, for reasons such as access, speed, or security.

Proxy Pattern Example

bank atm proxy thumb Proxy Pattern tutorial and RMI example

Let take ATM and Bank as our example. The bank has so many customers and the cost for accessing to the Bank is so high (cost for traveling to the bank, cost for paying receptionist…). So that they provide ATMs, and via the ATM, customer can use the IBank to interact with the bank. Forgive me if I’m not good at describing but I will explain this better in Java language wlEmoticon smile33 Proxy Pattern tutorial and RMI example

First I will create an iBank interface which define some basic interactions between customers and bank.

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

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface IBank {
	/**
	 * Check account and return current balance
	 * 
	 * @param accountId
	 * @return
	 */
	public double checkBalance(String accountId);

	/**
	 * Withdraw amt $ from bank and return new balance if success, if not return
	 * current balance.
	 * 
	 * @param accountId
	 * @param amt
	 * @return
	 */
	public double withDraw(String accountId, double amt);

	/**
	 * Deposite $amt into account, if success return new balance, if not return
	 * current balance.
	 * 
	 * @param accountId
	 * @param amt
	 * @return
	 */
	public double deposit(String accountId, double amt);
}

Then I will create a Central Computer for the Bank, this computer will hold all of account and do all transactions (supposed so)

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

import java.util.HashMap;
import java.util.Map;

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public class BankCentralComputer implements IBank {
	Map accounts = new HashMap();

	public BankCentralComputer() {
		accounts.put("12345", 20000.0);
		accounts.put("11223", 30000.0);
		accounts.put("33112", 60000.0);
	}

	@Override
	public double checkBalance(String accountId) {
		if (validateAccount(accountId)) {
			return this.accounts.get(accountId);
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	@Override
	public double withDraw(String accountId, double amt) {
		if (validateAccount(accountId)) {
			double currentBalance = this.accounts.get(accountId);
			double newBalance = currentBalance - amt;
			if (newBalance >= 0.0) {
				// Save account data
				this.accounts.put(accountId, newBalance);
				return newBalance;
			} else {
				System.out.println("You don't have enough money");
				return currentBalance;
			}
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	@Override
	public double deposit(String accountId, double amt) {
		if (validateAccount(accountId)) {
			double currentBalance = this.accounts.get(accountId);
			double newBalance = currentBalance + amt;
			this.accounts.put(accountId, newBalance);
			return newBalance;
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	boolean validateAccount(String accountId) {
		return this.accounts.containsKey(accountId);
	}

}

Now as it’s costly to use the Bank, they provide ATM everywhere for their customers

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

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public class ATM implements IBank {
	private IBank proxifiedBank;

	public ATM(IBank realBank) {
		if (realBank != null) {
			this.proxifiedBank = realBank;
		} else {
			this.proxifiedBank = new BankCentralComputer();
		}
	}

	@Override
	public double checkBalance(String accountId) {
		return this.proxifiedBank.checkBalance(accountId);
	}

	@Override
	public double withDraw(String accountId, double amt) {
		return this.proxifiedBank.withDraw(accountId, amt);
	}

	@Override
	public double deposit(String accountId, double amt) {
		return this.proxifiedBank.deposit(accountId, amt);
	}

}

As you can see, the ATM can do exactly what the Central Computer of the Bank do. Actually, the ATM  cannot do stuff like withDraw, deposit or checkBalance, but they have to ask another subject to do it. In this case if we construct the ATM without any specific real subject for it, it will use the Central Computer.

Now let’s see how some engineer will test the ATM at his weekend wlEmoticon smilewithtongueout7 Proxy Pattern tutorial and RMI example

Continue reading »

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 232011
 

You have probably heard of Session Façade when you join some class or course for Enterprise JavaBean (EJB). But can you tell how to implement the Façade Pattern? In this post I will help you.

What is Façade Pattern?

The Session Façade implements exactly the idea of Façade Pattern. Let’s see how the EJB-specs describes the Session Façade by giving us this picture:

facade design pattern session facade thumb Façade Design Pattern Tutorial

As you can see, the above picture now can give you a first look at the definition of Façade: It’s the way of wrapping and hiding the complicated details from the client. Instead it give the client a simpler interface to do the job.

And for the formal one, we can say that: Façade is a Structural Design Pattern to provide a simplified interface to a group of subsystems or a complex subsystem.

Façade Pattern Example:

Let’s give an example by watching how a computer boot-upfacade pattern computer boot thumb Façade Design Pattern Tutorial

A computer is combined of so many parts/devices like: the CPU, the memory (RAM/ROM), the storage unit (HDD,CD,USB Flash)…and many others.

The process of booting a computer is as follow: CPU, Memory and Hard Drive are turn on() and then the CPU freeze() to wait for instructions to load() in to memory. CPU will then execute() command by command to startup the OS.

That’s for the story. Now as always, I will demo the above story with some Java source code:

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 »