Sep 102011
 

You’ve seen the Observer Pattern where subscriber get notified from publisher about events when something happened. It’s about the Listener/ Observer, how about another famous pattern named “Callback Pattern”?

What is Callback Pattern?

I can tell you that there’s some similarity about the notification, but the Callback Pattern is very much “Architectural Pattern” and only these diagram and definition can help you to distinguish.

image thumb20 Callback Pattern with RMI Client Callback

Callback Pattern is an Architectural Pattern that allows a client to register with a server for extended operations. This enables the server to notify the client when the operation has been completed.

image thumb21 Callback Pattern with RMI Client Callback

What can Callback Pattern help you?

Use the Callback pattern for a client-server system with time-consuming client operations, and when one or both of the following are true:

  • You want to conserve server resources for active communication.
  • The client can and should continue work until the information becomes available. This can be accomplished with simple threading in the client.
Callback Pattern Example

This Design Pattern is an architectural pattern and needs a server/client application to apply, so I will use the same example in my previous post about Proxy Pattern using RMI for the demo. To save your time, I won’t tell the story again but you should read and run the RMI example first before taking the next step.

First, I will define a BankClientCallback interface, which will act as a standardized channel for the server to interact with the client.

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

import java.rmi.Remote;
import java.rmi.RemoteException;
/**
 * Callback Pattern with RMI tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BankClientCallback extends Remote {
	public void notifyAction(String action) throws RemoteException;
}

As you can see to allow the server to interact with the client, the client’s now actually a server, so it’s much like server-to-server conversation. Next is for the Server interface

Continue reading »

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 »

Sep 082011
 

You may hear of “Observer” or “Listener” somewhere especially when working with Swing or AWT. Do they have a difference? Some guys may even confuse between Observer and Listener, while actually they are the same concept in Java.

What is Observer Pattern?

Observer is a Behavior Design Pattern defined by GoF and the definition is maybe like this: “The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.” – from wiki.

Now let me take you to a closer look by observing an example:

observer pattern example thumb Observer Pattern Java Example

As you can read from the diagram, I will use a cellphone (BlackBerry in this case) to demonstrate this pattern. Each time there’s a call or an sms coming, a BlackBerry can notify you by multiple ways: via the ringtone, via a LED indicator or or via the Vibration…I treat these devices as the Observer object which will subscribe the SMSReceiver all the time for new SMS. If new SMS comes, these devices will be notified by the SMSReceiver to work accordingly.

Observer Pattern Example in Java

Now let’s see how we will explain the above example again in Java language.

blackberry sms receiver thumb Observer Pattern Java Example

First I will define the BBObserver object that can make BlackBerry device do something when some event happens.

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

/**
 * Observer pattern example by searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BBObserver {
	public void handleEvent();
}

Next is for the BBObservable object that can contain a list of subscriber object, and when some other objects tell it, it will notify all other subscribers about the event.

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 »

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 »