Tuesday, 4 November 2008

Design Patterns

1. Singleton

Possibly the simplest design pattern is the singleton, which is a way to provide one and only one object of a particular type. 
Sample code
==========================================
final class Singleton {
  private static Singleton s = new Singleton(47);
  private int i;
  private Singleton(int x) { i = x; }
  public static Singleton getReference() {
    return s;
  }
  public int getValue() { return i; }
  public void setValue(int x) { i = x; }
}
==========================================
Points:
1. Must make all constructors private 2. create at least one constructor to prevent the compiler from synthesizing a default constructor
3. We should protect the class by cloning also, so the final is been used.
Double Checked Locking in Sigleton Pattern
public static Singleton CreateInstance() {    
if(instance == null) 
//first check   {       
// Use a mutex locking mechanism  that suits your system       
LockCriticalSection();        
if (instance == null) 
//second check       {         
instance = new Singleton();       
}       
UnLockCriticalSection();    
}    
return instance;
}
2. Strategy Pattern: Choosing the algorithm at run time
3. Template Pattern: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Example, all servlets, JSPs, Thread
Some questions
==========================================
1. Structurally, the difference between Proxy and State is simple: a Proxy has only one implementation, while State has more than one. The application of the patterns is considered (in Design Patterns) to be distinct: Proxy is used to control access to its implementation, while State allows you to change the implementation dynamically.
2. Difference between AbstractFactory and Factory
Abstract Factory:- provide an interface to create a family of related or  dependant classes without specifying their concrete classes. Abstract factory pattern is typically used for giving implementation to specification (eg., jdbc, servlet specifications etc...).

Factory Method :-  another creational pattern, Defines an interface for creating An Object, but let sub class decide which class to instantiate.


Post a Comment