Saturday, March 9, 2013

Visitor pattern and Strategy Pattern


Visitor-

 - separate algorithm from object, which provides ability to add new feature without modifying the structure.
 - works on double dispatch principle.
 - Isolate the behavior from original class and provide it in other visitor class
 - pass the visitor object to the class, and then use this object to execute the behavior
 -Ex - there is a printer and we want to print from a machine.
precondition - every machine should have ExecutePrint method,hence we can have an interface for this.
printer will have overridden method for printing from different kind of machines.
pseudo code -
desktop m1 = new desktop ();
Printer p = new Printer();
m1.ExecutePrint(p);//accept
Printer{
Print(desktop d1){// print for desktop}
Print(laptop l1){// print for laptop}
}
Desktop{
  ExecutePrint(Printer p)
 {
    p.Print(this);//visit
 }
}
laptop{
   ExecutePrint(Printer p)
   {
      p.Print(this);
   }
}

Strategy -
Isolate the behavior using interface.
- every class will call behavior using interface only, at run time the object of concrete class(implementing interface) will be passed.
- At run time we can decide which kind of object we want to pass, as the whole implementation is done using interface, so any kind of object for which this interface is been implemented, can be passed.
- Example-
Say there is interface IBehavior , and all behaviors implement this.
Behavior1 : IBehavior {}
Behavior2 : IBehavior {}

Now the classes will use IBehavior in its implementation and when we are trying to create the object of the class, we can pass the object of either Behavior1 or Behavior2 and then the object will execute the code accordingly.

No comments:

Post a Comment