Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

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:

Monday, January 3, 2011

Adapter : Design Pattern

- Translates one interface for a class into a compatible interface.

Two Kinds of Adapter Patterns
Object Adapter :  Adapter has reference/instance of  Adaptee
Class Adapter :  Adapter uses Adaptee by subclassing. i.e. Adapter extends both Target and Adaptee.  
                         ( Multiple inheritence not possible in java )


(Below is about Object Adapter)
AC: Target
DC 5 AMP:  Adaptee








public interface AC {
    public void doOp();
}


public class AC5AMP implements AC {
   
    public void doOp() {
        System.out.println("Concrete Target");
    }
}


public class DC5AMP {
   
    public void doOp() {
        System.out.println("Concrete Adaptee");
    }
}


public class AC_ADAPTER implements AC {
    private DC5AMP oldSocket;
   
    public AC_ADAPTER( DC5AMP arg) {
        oldSocket = arg;
    }
   
    public void doOp() {
        oldSocket.doOp();
    }
}


public class Client {
    public static void main( String [] args) {
       
        DC5AMP dcSocket = new DC5AMP();

        AC_ADAPTER ac_socket = new AC_ADAPTER(dcSocket);
        ac_socket.doOp();

    }
}

Decorator : Design Patterns

  • The decorator pattern helps to add behavior or responsibilities to an object.
  • This is also called “Wrapper”.
  • Suppose we have some 6 objects and 2 of them need a special behavior, we can do this with the help of a decorator.
  • Decorators should be abstract classes and the concrete implementation should be derived from them.



- Examples:
- Christmas tree : There is a need to decorate a Christmas tree. Now we have many branches which need to be decorated in different ways.
- Soft Cone Mixture
- Coffee Mixture
- Different Windows in a common window

Q. The "Adapter" pattern is also known as "Wrapper" pattern (WrapperPattern). Is Wrapper/Adapter/Decorator the same pattern?
A. No. AdapterPattern is used to convert the interface of an object into something else. DecoratorPattern is used to extend the functionality of an object while maintaining its interface. Both of these are probably sometimes called WrapperPattern since both of them do "wrap" an object.

Q. Decorator and Subclassing
A. Subclassing works fine but there are cases in which it is not appropriate or practical. If you want a behavior for several components, then you end up with many subclasses. As your code grows more complicated, having too many subclasses creates maintenance problems and makes your code more error-prone. You must also reproduce all of the parent class constructors that your subclass needs to support. In cases like this, it is better to use the Decorator pattern.

Difference that we see between a decorator pattern and subclassing is that we can decorate any class that implements an interface with a single class.


Example: A dress that you keep on making by adding features like emobroydree, satinlace etc.

public interface Dress {
   public int cost = 0;
   public int getCost();
}

public class SimpleDress implements Dress {
   private int cost = 10;
   public int getCost() {
     return cost;
   }
}

public abstract class DecoratorDress implements Dress {
   protected Dress mydress;

   DecoratorDress(Dress dress) {
      mydress = dress;
   }

   public int getCost() {
      return mydress.getCost();
   }
}

public class Embroydree extends DecoratorDress {
   private int cost = 20;

   public Embroydree(Dress dress) {
      super(dress);
      cost = cost + dress.getCost();
   }

   public int getCost() {
      return cost;
   }
}


public class SatinLace extends DecoratorDress {
   private int cost = 20;
   public SatinLace(Dress dress) {
      super(dress);
      cost = cost + dress.getCost();
   }

   public int getCost() {
      return cost;
   }
}

public class Client {
    public static void main( String [] args) {

       Dress newDress = new SimpleDress();
       newDress = new Embroydree(newDress);
       newDress = new SatinLace(newDress);
       System.out.println("Cost : " + newDress.getCost());
   }
}