marți, 26 octombrie 2010

Visitor Pattern

Visitor Pattern

About

  • defines and performs new operations on all the elements of an existing structure, without altering its classes
  • the visitor design pattern is a way of separating an algorithm from an object structure it operates on
  • using the visitor pattern allows to conform with the open/closed principle
    • "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"
    • inheritance
    • use interfaces/abstract classes -- change the implementation if it is needed / multiple implementation could be created


Client:
  • initiate and manage the element (objectStructure)
  • Call Visitor methods on objectStructure
Visitor:
  • Classes that contain methods that iterate through the object structure and apply operations to its elements
Element1, Element2
implements an Accept operation that takes a visitor as an argument

class ConcreteElementA : Element
{
  public override void Accept(Visitor i_visitor)
  {
    visitor.VisitElement1(this);
  }
...
}


Samples:
  • Animals that do different things: barks, run, ...
  • Different operation (getWage(), getPTO() ) on different type of employees (manager, programmer, tester)

Visitor Pattern in C#:

  • System.Reflection API
    • Viewing metadata
    • Performing type discovery
    • Late binding to methods and properties
    • Creating types at runtime with Reflection.Emit
            Type[]: Will hold a list of type names
            GetType( )Will return a class name
            MethodInfoCan return all parameters and the return type of a method
            InvokeWill call the method described in a variable of type MethodInfo

  • Use Visitor Pattern to do different operation on tree (binary tree)

Shortcomings of the Visitor pattern

  • The return type of visiting methods have to be known in advance. 
  • A lot of code has to be written to prepare the use of visitors: the visitor class with one abstract method per class, and a accept method per class. This code is tedious and boring to write. 
  • If a visitor pattern has not been written in the first time, the hierarchy has to be modified to implement it.

Niciun comentariu:

Trimiteți un comentariu