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 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 »

Aug 202011
 

chain of responsibility design pattern 1 thumb Chain Of Responsibility Pattern Tutorial

If the above diagram doesn’t give you enough definition about the Chain of Responsibility. Here is a good one: The Chain of Responsibility is a Behavior Design Pattern “to establish a chain within a system, so that a message can either be handled at the level where it is first received,
or be directed to an object that can handle it”

java chain of responsibility thumb Chain Of Responsibility Pattern Tutorial

This design pattern will help you to divide an abstract job (Declare in Handler) into specific tasks that can be completed by Concreted Handler.

Now I will give you a small example for better understanding:

java chain of responsibility diagram thumb Chain Of Responsibility Pattern Tutorial

Suppose that we have a Client (Hungry Customer) who enter a Restaurant (Food Processor) and said: “Hey, give me a Vegetarian Dish”. The Clerk (CookerHandler) in the restaurant will ask the Customer for type of Food and then forward the job either Vegetarian Cooker or Non-Vegetarian Cooker, but somehow he gave it to Non-Vegetarian-Cooker first. So in this case, the message first received by the Clerk but forwarded to the specific skillful Cooker later.

Let’s see how we can demonstrate them in Java:

First we define the Dish that will contain the result of  the cooking.

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

/**
 * Chain of Responsibility Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class Dish {
	private String name;
	private boolean vegetarian;
	private double price;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isVegetarian() {
		return vegetarian;
	}

	public void setVegetarian(boolean vegetarian) {
		this.vegetarian = vegetarian;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

}

Continue reading »

Aug 202011
 
Java Search String For Index

Java has very good methods for searching a sub string within another string: indexOf and lastIndexOf. In this part I will demonstrate the uses of these methods.

package net.searchdaily.java.string.common;

/**
 * Java String Search. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class JavaSearchString {
	public static void main(String[] args) {
		// the given string to search
		String stringText = "Java String to execute the String Search methods";
		String textToSearch = "String"; // we will search for "String" in the
										// stringText

		int foundPosition = stringText.indexOf(textToSearch);

		System.out.println("I found: " + textToSearch + " in " + stringText
				+ " at the position: " + foundPosition);
	}
}

In the above example, the result will be 5 as it the first location where String is found in the text “Java String to execute the String Search methods”

image thumb70 Java String common uses part 2

How about the case when search string cannot be found? the indexOf method will return a negative number (-1). See it in the next example where I use the same example above to search for String starts from specific location.

Continue reading »

Aug 172011
 
Java String split

Split is one of the most use methods of Java String to split a string to match a certain regular expression. Observe the following example:

package net.searchdaily.java.string.common;

/**
 * This is an indepth-example of Java String to demonstrate all features of this
 * class. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class StringSplitExample {
	public static void main(String args[]) {

		/* String to split. */
		String str = "java-string-to-split";
		String[] tempString;

		// delimiter
		String delimiter = "-";
		// given string will be split.
		tempString = str.split(delimiter);
		// print the result
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

		/*
		 * ATTENTION : Some special characters need to be escaped while
		 * providing them as delimiters like "." and "|".
		 */

		System.out.println("");
		str = "java.string.to.split";
		delimiter = ".";
		tempString = str.split(delimiter);
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

		// The second parameter of the split method can help to determine the
		// number of maximum elements to split.

		System.out.println("");
		tempString = str.split(delimiter, 3);
		for (int i = 0; i < tempString.length; i++)
			System.out.println(tempString[i]);

	}
}

As you can guess, here is the final result:

image thumb46 Java String common uses

Java String to Int

There are several ways to convert from a String to Integer, the first and most use is to use Integer.parseInt() method from the Integer class.

package net.searchdaily.java.string.common;

/**
 * Convert Java String into Integer. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class StringToInt {

	public static void main(String[] args) {
		String stringText = "2011";
		int intVar = 0;
		try {
			intVar = Integer.parseInt(stringText);
		} catch (NumberFormatException nfe) {
			System.out.println("NumberFormatException: " + nfe.getMessage());
		}
		// now do some integer operation
		intVar++;
		System.out.println(intVar);
	}

}

Yes the result of the above conversion is 2012, but please remember to catch the exception because the parseInt() method will throw some NumberFormatException if the stringText is not a well-numeric-format.

Continue reading »