Friday, February 24, 2012

More Patterns-2

The Decorator Pattern attaches additional responsibilities to an object dynamically. It provides a flexible alternative to subclassing for extending functionality.
Decorators (java.io is a good example):
  • Have same supertype as the objects they decorate
  • You can use one or more decorators to wrap an object
  • Objects can be decorated at runtime
  • The decorator adds its own behaviour either before and/or after delegating to the object it decorates to do the rest of the job
  • Can make code complex and cause problems if not well-thought, need to be careful before using it
Decorator pattern = responsibility. New responsibilities or behaviours are added to the design, without altering existing code.

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which classes to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory employs two parallel class hierarchies: the creator classes and the product classes. The pattern isolates object creation and reduces object dependency.

he Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

To prevent problems with multi-threading in Singleton creation, you can:
  • Synchronise the getInstance method. This is expensive, but is easy and can be done if we don’t expect it to be called many times
  • Use eager instantiation of the instance, if that is not too expensive and we expect Singleton to be definitely used early on
  • Use “double-check locking”. Can be done only in Java 5 and greater and can be an overkill
public class Singleton {
    private volatile static Singleton uniqueInstance;
    private Singeton() { }
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            synchronized(Singleton.class){
                if(uniqueInstance==null){
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

The Command Pattern encapsulates the request as an object, thereby letting you parameterise other objects with different requests, queue or log requests, and support undoable operations.
Think of command as a waiter carrying requests from customer to chef for execution. Command itself does less work, with most of the work offloaded to an encapsulated class.
public interface Command {
 public void execute();
}


No comments: