Thursday, 6 February 2014

[Java] Visitor Design Pattern in Java

Visitor Design Pattern

In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to easily follow the open/closed principle. (from Wikipedia)
  • Open/Closed Principle
In object-oriented programming, the open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“;[1] that is, such an entity can allow its behaviour to be modified without altering its source code. This is especially valuable in a production environment, where changes to source code may necessitate code reviews, unit tests, and other such procedures to qualify it for use in a product: code obeying the principle doesn’t change when it is extended, and therefore needs no such effort. (from Wikipedia)

When to use the visitor pattern

  1. Current class and object structure is fixed, and can’t make changes to it. But you do need to add new operations to that hierarchy. The dilemma is that you want to add operations to the base class, but you can not modify the base class
  2. Some unrelated operations need to be added on objects in an object structure, but you don’t want to add each operation in each object to let the class messed, and hope a good structure of class
  3. Object structure is seldom changed, but the operations may be added or modified frequently. Similar to 1
  4. Classes in object structure have difference interfaces and you expect that which operation is performed depends on its concrete class.

How to use visitor pattern (Take AST as an instance)

  • All nodes have the similar operations (such as getDeclName, getSchText). For example, DeclNamePrint will traverse AST and print the word-parts of all declaring names (DeclName)
  • To add this operation, define a new Visitor class first

Right Example

CZT (Community Z Tool) project uses the visitor pattern to separate the structure of a set of AST (Annotated Syntax Tree) node from the operations performed on these nodes.
  • CZT has the defined inheritance hierarchy, and different kinds of nodes, such as paragraph, schema, and reference.

Reference:

No comments :

Post a Comment