Saturday, January 8, 2011

List of Design Patterns


Creational patterns

These patterns have to do with class instantiation. They can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation to get the job done.
  • Abstract Factory groups object factories that have a common theme.
  • Builder constructs complex objects by separating construction and representation.
  • Factory Method creates objects without specifying the exact class to create.
  • Prototype creates objects by cloning an existing object.
  • Singleton restricts object creation for a class to only one instance.
  • Multiton restricts object creation for a class to only one instance per given key.

[edit]Structural patterns

These concern class and object composition. They use inheritance to compose interfaces and define ways to compose objects to obtain new functionality.
  • Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
  • Bridge decouples an abstraction from its implementation so that the two can vary independently.
  • Composite composes zero-or-more similar objects so that they can be manipulated as one object.
  • Decorator dynamically adds/overrides behaviour in an existing method of an object.
  • Facade provides a simplified interface to a large body of code.
  • Flyweight reduces the cost of creating and manipulating a large number of similar objects.
  • Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

[edit]Behavioral patterns

Most of these design patterns are specifically concerned with communication between objects.
  • Chain of responsibility delegates commands to a chain of processing objects.
  • Command creates objects which encapsulate actions and parameters.
  • Interpreter implements a specialized language.
  • Iterator accesses the elements of an object sequentially without exposing its underlying representation.
  • Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
  • Memento provides the ability to restore an object to its previous state (undo).
  • Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
  • State allows an object to alter its behavior when its internal state changes.
  • Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
  • Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
  • Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.

Bridge : Design Pattern

The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently" [1]. The bridge uses encapsulationaggregation, and can use inheritance to separate responsibilities into different classes.


In basic,  in the abstract class, keep the stuf you will never override and in concrete stuff add non-commmon implementations in concrete section


In below example, each of abstactions method can be overridden by refined/concrete abstraction. The implementor references the Abstration and hold function that would be common for that abstraction. The concrete implementation add on extra functinality.




































public abstract class TV {
public void On() {}
public void Off() {}
public void tuneChannel(int channel) {}
}

public class Sony extends TV {
public void On() {
//Sony way of off
}
public void Off() {
//Sony way of ON
}
public void tuneChannel(int channel) {
System.out.println("Channel switched to : " + channel);
//Sony way of setting channel
}
}

public abstract class RemoteControl {
private TV tv;
RemoteControl(TV args) {
tv = args;
}
public void on() {
tv.On();
}
public void off() {
tv.Off();
}
public void setChannel(int channel) {
tv.tuneChannel(channel);
}
}

public class SonyRemote extends RemoteControl {
int channelNo = 0;
public SonyRemote(TV tv) {
super(tv);
}
public void nextChannel() {
channelNo++;
setChannel(channelNo);
}
}





public class Client {
public static void main(String [] args) {
Sony sony = new Sony();
SonyRemote remote = new SonyRemote(sony);
remote.nextChannel();
remote.nextChannel();
remote.nextChannel();
}
}

References:




Thursday, January 6, 2011

Composite Pattern: Design Pattern

Whole-Part hierarchical relationship.

















public interface Component {
    public void print();
}


public class Leaf implements Component {
    String name = "";
    public Leaf(String args) {
this.name = args;
    }
    public void print() {
System.out.println(">> " + this.name);
    }
}


public class Composite implements Component {
    String name = "";
    int index = 0;
    Component childrens[] = new Component[10];


    public void addComponent(Component arg) {
childrens[index++] = arg;
    }

    public Composite(String args) {
this.name = args;
    }


    public void print() {
System.out.println(">> " + this.name);
for (int i = 0; i < index; i++) {
          childrens[i].print();
}
    }
}


public class Client {
    public static void main(String [] args) {
         Composite main = new Composite("MAIN");
         Leaf leaf1 = new Leaf("LEAF1");
         main.addComponent(leaf1);
         Composite subMain = new Composite("subMAIN");

         Leaf leaf2 = new Leaf("LEAF2");
         Leaf leaf3 = new Leaf("LEAF3");
         subMain.addComponent(leaf2);
         subMain.addComponent(leaf3);
         main.addComponent(subMain);

         main.print();
    }
}


References:
http://sourcemaking.com/design_patterns/composite

Wednesday, January 5, 2011

Flyweight : Design Pattern

- Flyweight design pattern
   1. Identify shareable state (intrinsic) and non-shareable state (extrinsic)
   2. Create a Factory that can return an existing object or a new object f(containing sharable state)
   3. The client must use the Factory instead of “new” to request objects
   4. The client (or a third party) must provide/compute the extrinsic state
  




 






- Basically in simple language. Keep classes with sharable state as a factory. Whenever a client request for a state, give it back the same instance of the state. If you have three different states, always keep giving back those 3 refrences to states based on input state type.   i.e  if all of the objects share some intrinsic, invariant information that is constant among all of them, it can be removed from each object, and referenced. 

Above eliminates the redundancy of having to repeat the same invariant, intrinsic information for each object, so instead of storing the same information n times for n objects, it is only stored once. This object that contains all of the intrinsic information is called a flyweight object.

- It is possible for a flyweight to have extrinsic information as well. This information must be stateless and determined by context, having no stored values, but values that can be calculated on the spot. This separation into extrinsic and intrinsic information allows great numbers of similar objects to exist, differing only in the context in which they exist.

- The different components involved in the Flyweight Pattern are the Flyweight, the ConcreteFlyweight, the FlyweightFactory and the Client.

The Flyweight itself is the set of intrinsic information that a set of objects share in common. It is abstract.

The ConcreteFlyweight is a subclass of the Flyweight, and contains all of its information, as well as how to calculate extrinsic information for a particular (yet arbitrary) object. It is shared among more than one object.

The FlyweightFactory serves to dispense particular flyweights requested. When a Flyweight with certain properties is requested, it checks to see if one already exists, and if so, returns that flyweight. If the requested flyweight does not exist, it creates the requisite flyweight, stores it, and then returns it.

The Client, in creating a new object, must assign a flyweight to it, so it asks the FlyweightFactory for a particular flyweight, receives that flyweight, and creates a reference to it in the object it is creating.


Clients don't directly instantiate flyweights; instead they get them from a factory. The factory first checks to see if it has a flyweight that fits specific criteria (e.g., a blue or white line); if so, the factory returns a reference to the flyweight. If the factory can't locate a flyweight for the specified criteria, it instantiates one, adds it to the pool, and returns it to the client.


To decide if some part of your program is a candidate for using Flyweights, consider whether it is possible to remove some data from the class and make it extrinsic. If this makes it possible to reduce greatly the number of different class instances your program needs to maintain, this might be a case where Flyweights will help.


public abstract class Flyweight {
public abstract void printState();
}



public class ConcreteFlyWeight extends Flyweight {
//This flyweight stores state
String state ;

public ConcreteFlyWeight(String val) {
this.state = val;
}
public void printState() {
System.out.print(", STATE: " + state);
}


public String getState() {
return state;
}
}



public class FactoryFlyWeight {
  ConcreteFlyWeight weights[] = new ConcreteFlyWeight[2];

int count = 0;

public ConcreteFlyWeight getFlyweight(String argState) {
       if (count > 0) {
          for (int i = 0; i < count; i++) {
              if (argState.equals(weights[i].getState())) {
                  return weights[i];
              }
          }
      }
      weights[count] = new ConcreteFlyWeight(argState);
      return weights[count++];
  }
public int getStateCount() {
return count;
}
}


public class OrderNo {   //extrinsic function
private int orderNo = 0;

public OrderNo(int val) {
this.orderNo = val;
}

public int getOrderNo() {
return this.orderNo;
}

}



public class Client {
static ConcreteFlyWeight [] concreteFly = new ConcreteFlyWeight[100];
static OrderNo [] orders = new OrderNo[100];
static int inputCount = 0;
static FactoryFlyWeight factory;

public static void takeOrder(String arg, int orderNo) {
concreteFly[inputCount] = factory.getFlyweight(arg);
orders[inputCount] = new OrderNo(orderNo);
inputCount++;
}

public static void main( String [] args) {
factory = new FactoryFlyWeight();
takeOrder("RED", 1);
takeOrder("BLUE", 1);
takeOrder("BLUE", 2);
takeOrder("RED", 3);

  for (int i = 0; i < inputCount; i++) {
  System.out.println("");
          System.out.print("ORDER NO: " + orders[i].getOrderNo());
  concreteFly[i].printState();
  System.out.println("");
  }  
  
       System.out.println("");
  System.out.println("No of flyweight in action: " +        factory.getStateCount());
}
}


References"
http://www.javaworld.com/javaworld/jw-07-2003/jw-0725-designpatterns.html?page=2
http://www.exciton.cs.rice.edu/javaresources/designpatterns/flyweightpattern.htm
http://sourcemaking.com/design_patterns/flyweight
http://www.fluffycat.com/Java-Design-Patterns/Flyweight/

Tuesday, January 4, 2011

Singelton : Design Pattern

 - Allows to create a unique object by giving a global point of access, ensuring object is created only when is required.
- Constructor is declared private, hence class cannot be subclassed/ extended.
 

// A Thread Safe Singelton Example, Lazy creation

public class Singleton {
     private static Singleton myInstance = null;
     
     private Singleton() { }

     public static synchronized Singleton getInstance() {
          if ( myInstance ==  null ) {
                myInstance = new Singleton();
         }
         return myInstance();
    }
}


// Egarly created thread safe example. Thread safe delegated to JVM

public class Singleton {
      private static Singleton myInstance = new Singleton();
   
      public static getInstance() {
           return myInstance();
     }
}


Difference between Singleton and Static Class

- Singleton can extend classes and implement interfaces, while a static class cannot (well, it can extend classes, but it does not inherit their instance members). 
- Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded. A sinlgeton class can be extended and it's methods overidden.
- Singletons can be handled polymorphically without forcing their users to assume that there is only one instance. For instance, assume you have a Configuration class that holds some global configs. Methods that use this configuration information may be defined as:

public void doSomething(Configuration config) {...}

When you start writing your system you may have only one global instance, so you make Configuration a singleton. But at some later point you may want to support more than one configuration set. Maybe you'd want to allow the user to load a Configuration object from and external file or or programmaticaly create his own (this happened in my code several times). Provided that the classes or methods that use a configuration object allow the user to pass his own instance, most of your code need not be aware of the "global" nature of the class and is therefore more flexible.

References:

Facade : Design Pattern

  • Façade provides a simplified interface while still exposing the full functionality of the system to those who may need it.
  • Façade is free to add functionality in addition to using existing subsystem
  • Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.

You, as client want access to different goods. You do not know where the different materials are stored. You just have access to store keeper who knows his store well. Whatever you want, you tell the store keeper and he takes it out of store and hands it over to you on showing him the credentials. Here, the store keeper acts as the facade, as he hides the complexities of the system Store.















The classes and/or objects participating in this pattern are:
  • Facade   (MortgageApplication)
    • knows which subsystem classes are responsible for a request.
    • delegates client requests to appropriate subsystem objects.
  • Subsystem classes   (Bank, Credit, Loan)
    • implement subsystem functionality.
    • handle work assigned by the Facade object.
    • have no knowledge of the facade and keep no reference to it.

References:

Proxy : Design Pattern

- Proxy represents a standin object for the real object.  
- This is required when the real object is complex to create, is not available, or for authentication purpose.   
- For e.g. web service proxy, proxy authentication server etc.

- If creation of object is expensive, its creation can be postponed till the very need arises and till then, a simple object can represent it.



- A client obtains a reference to a Proxy, the client then handles the proxy in the same way it handles RealSubject and thus invoking the method doSomething(). At that point the proxy can do different things prior to invoking RealSubject’s doSomething() method. The client might create a RealSubject object at that point, perform initialization, check permissions of the client to invoke the method, and then invoke the method on the object. The client can also do additional tasks after invoking the doSomething() method, such as incrementing the number of references to the object.
 
Common Situations where the proxy pattern is applicable are:
  • Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand (For example creating the RealSubject object only when the doSomething method is invoked).
  • Remote Proxies: providing a local representation for an object that is in a different address space. A common example is Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object (called skeleton) found on a different machine.
  • Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.
  • Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.




Example: Virtual Proxy












public interface Access {
    public String getAccess();
}
public class RealAccess implements Access {
    String status = "";
   
    RealAccess(String arg) {
        status = arg;
    }
   
    public String getAccess() {
        return status;
    }
}

public class ProxyAccess implements Access {
    String status = "";
    RealAccess orgAccess = null;
   
    ProxyAccess(String arg) {
        status = arg;
    }
   
    public String getAccess() {
        if ( orgAccess == null ) {
            orgAccess = new RealAccess(status);
        }
        return orgAccess.getAccess();
    }
}

public class Client {
    public static void main( String [] args) {
        Access diskAccess = new ProxyAccess("33344");
        System.out.println("ACCESS CODE: " + diskAccess.getAccess());
    }
}




Q. Difference between Adapters and Proxy
A.  The Adaptor pattern is used when you want to use a class that isn't useable in that particular context. The Proxy pattern is used when you have a class that can be used in the particular context, but for whatever reason it is too heavy or slow.

In the proxy pattern, the RealSubject and the Proxy both have the same interface, the Proxy is acting as a stand in for the RealSubject. In the Adaptor pattern, the Target and the Adaptee have different interfaces
and the Adaptor is converting requests from one interface to the other.


Q. Difference between Decorators and Proxy
A. Decorators never ever instantiate their surrogate objects. Decorators are always passed their surrogates in their constructors and perform actions on these surrogates.
Proxies on the other hand always obtain an instance of their surrogates (either via constructors or factories). Proxies therefore never really expose their underlying objects but decorators do.



PatternDescription
DecoratorWraps another object and provides aditional behaviour to it
ProxyWraps another object to control access to it
AdapterWraps another object and provides a different interface to it
FacadeWraps a bunch of object to simlify there interface

References used: