Tuesday, November 07, 2006
Decorator Design Pattern
1. Make a responsibility easily added and removed dynamically.
2. More flexibility than static inheritance.
3. Provide an alternative to sub classing.
4. Add new function to an object without affecting other objects.
5. Transparent to the object.
What is Decorator Pattern :
Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper. Suppose we have some 10 objects and 2 of them need a special behavior, we can do this with the help of a decorator. The decorator pattern can be use wherever there is a need to add some functionality to the object or group of objects.
Java Design Patterns suggest that Decorators should be abstract classes and the concrete implementation should be derived from them.
Example of Decorator Pattern:
Christmas tree branches need to be decorated with the different types of branches.
package test.structural.decorator;
public abstract class Decorator {
// This method is used to decorate the branch of the Christmas tree
public abstract void place(Branch branch);
} // End of class
Above class has method place which places different types of items on the branches of the tree.
package test.structural.decorator;
public class ChristmasTree {
private Branch branch;
//returns the branch
public Branch getBranch() {
return branch;
}
} // End of class
You decorate the branches in three different ways; one is by putting different color balls on them, by putting different color squares on them and also by putting stars on them.
Implementation of one of the above three decorator will as below
package test.structural.decorator;
// Decorates the branch of the tree with different color balls.
public class BallDecorator extends Decorator {
public BallDecorator(ChristmasTree tree) {
Branch branch = tree.getBranch();place(branch);
}
//The method places each decorative item on the tree.
public void place(Branch branch) {
branch.put("ball");
}
}// End of class
Same way you can write the SquareDecorator and StarDecorator.
Instantiation of the BallDecorator will be like
BallDecorator decorator = new BallDecorator(new ChristmasTree());
Ball decorator will be instantiated and a branch of the Christmas tree will be decorated with different color balls.
This pattern provides functionality to objects in a more flexible way rather than inheriting from them. Disadvantage of the decorator pattern will be maintenance of the code as lots of similar looking small object for each decorator.
Monday, November 06, 2006
Bridge Design Pattern
1. Share the implementation among the multiple objects
2. Wants to improve extensibility.
3. Wants to share the abstraction and implementation permamantly.
4. Hide the implementation details from client.
What is Bridge Design Pattern :
Bridge pattern decouples the interface from its implementation. Doing this gives the flexibility so that both can vary independently.
Example of Bridge Design Pattern :
The switch is the interface and the actual implementation is the starting of the Television once it’s switched-on. Still, both the switch and the Refrigerator are independent of each other. Another switch can be plugged in for the Refrigerator and this switch can be connected to start Television
package structural.bridge.test;
public interface Switch {
public void switchOn(); //to switch on
public void switchOff(); //to switch off
}
This switch can be implemented by various devices in house, as Television, Refrigerator etc. Here is the sample code for that.
Package structural.bridge.test;
public class Television implements Switch { // implements switch interface
// On position of switch.
public void switchOn() {
System.out.println("Television Switched ON");
}
// Off position of switch.
public void switchOff() {
System.out.println("Television Switched OFF");
}
}
Package structural.bridge.test;
public class Refrigerator implements Switch { // implements switch interface
// On position of switch.
public void switchOn() {
System.out.println("Refrigerator Switched ON");
}
// Off position of switch.
public void switchOff() {
System.out.println("Refrigerator Switched OFF");
}
}
The interface Switch can be implemented in different ways. Switch as an interface as it has only two functions, on and off. But, there may arise a case where some other function be added to it, like change () (change the switch).You need to make the decision earlier to implementation whether the interface should be interface or abstract class.
Friday, November 03, 2006
Transfer Object Design Pattern
Benefits of Transfer Object Pattern
1. Fetch multiple values in one trip.
2.Decrease network traffic.
3.Get related values from remote business method.
4. Minimize latency and server resource usage.
What is Transfer Object Pattern?
A transfer object is a serializable class that groups related attributes, forming a composite value. This class is used as the return type of a remote business method. Clients receive instances of this class by calling coarse-grained business methods, and then locally access the fine-grained values within the transfer object. Fetching multiple values in one server roundtrip decreases network traffic and minimizes latency and server resource usage.
Example of Transfer Object
The EmployeeDetails and EmployeeTO transfer objects.
Sample application class EmployeeAdminFacade has a method getEmployeeInfo that returns an immutable, serializable collection of EmployeeDetails objects, each of which is a transfer object that represents data from an employee. The collection returned by method getEmployeeInfo is also a transfer object, because the values it contains are always accessed together where they are used. This hierarchical transfer object is implemented by class EmployeeTO.

Above Figure shows the structure of the EmployeeTO transfer object. Class mutableEmployeeTO, which extends a serializable ArrayList, contains a collection of EmployeeDetails objects. But because MutableEmployeeTO extends ArrayList, it is mutable. Transfer objects should be immutable so that clients do not unintentionally change their contents. Interface EmployeeTO adapts the MutableEmployeeTO collection, allowing read-only access to the collection while preventing modifications.
The definition of the EmployeeTO interface follows.
public interface EmployeeTO extends Serializable {
public Iterator iterator();
public int size();
public boolean contains(Object o);
public boolean containsAll(Collection c);
public boolean equals(Object o);
public int hashCode();
public boolean isEmpty();
public Object[] toArray();
public Object[] toArray(Object[] a);
static class MutableEmployeeTO extends ArrayList implements EmployeeTO { }
} //end of the interface
The EmployeeTO interface is clearly a collection, since it defines the Java collection methods. The collection is immutable, because it has no methods that would allow the collection contents to be changed. An example of using EmployeeTO appears in method EmployeeAdminFacadeEJB. getEmployeeInfo, shown below. The method constructs a EmployeeTO.MutableEmployeeTO object and populates it with EmployeeDetails instances. Note that the return type of getEmployeeInfo is EmployeeTO, so callers can access only methods that read the collection contents, and not methods that would change them.
public EmployeeTO getEmployeeInfo(int employeeId) throws Exception {
EmployeeTO.MutableEmployeeTO retVal = new EmployeeTO.MutableEmployeeTO();
EmployeeManagerLocal mgr = getEmpMgr();
try {
EmployeeLocalHome pohome = getEmpInfo();
Collection employee = mgr.getEmpById(employeeId);
Iterator it = employee.iterator();
while((it!= null) && (it.hasNext())) {
....... // Access and format data
retVal.add(new EmployeeDetails(employeeId, joiningDate,salary,department));
}
} catch (FinderException fe) {
... // process exception
}
return(retVal);
} //end of method
The details for a single employee are contained in an immutable, serializable transfer object of type employeeDetails It is a typical transfer object for a single composite value, containing private fields and public, read-only property accessors, as shown in the following code sample.
public class EmployeeDetails implements java.io.Serializable {
private int employeeId;
private Date joiningDate;
private float salary;
private String department;
public EmployeeDetails(int employeeId, Date joiningDate, float salary, String department) {
this.employeeId = employeeId;
this.joiningDate = joiningDate;
this.salary = salary;
this.department = department;
}
public int getEmployeeId() { return employeeId; }
public Date getJoiningDate () { return joiningDate; }
public float getSalary () { return salary; }
public String getDepartment () { return department; }
}
Thursday, November 02, 2006
Flyweight Design Pattern
1. Increase runtime cost associated with transferring, finding, or computing extrinsic data.
2. Reduce the number of objects created, decrease memory footprint and increase performance.
3. Need to instantiate a large amount of small and fine-grained classes.
4. An object extrinsic state can be shared by classes.
Example of Flyweight design pattern
In Java string class is designed with Flyweight design pattern. When you create a string constant, such constant is stored in a pool. When the second string is created, it will be checked to see if it has been created. If it is true, the second string instance will be picked up from the string pool instead of creating a new one.
String str1 = "test"; //
String str2 = "test"; // stored in the string pool.
String str3 = new String("test");
System.out.println(str1==str2); //true, as it shares the same memmory address
System.out.println(str1==str3); //false
Flyweight pattern uses the momory on fly. Another example would be like , you would like to display a folder structure with different subfolder which internally contains sub folders , files and so on. In this case we display only first level folder and display the subfolder on the fly when user clicks on the subfolder.Apply the same for subfolder too , hence objects are created on runtime increasing perfomance and reducing memory.