Visitor Generic
|
|
|
Visitor Design pattern in Java using Generics
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure it operates on. 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.
Objectives :
- Visitable classes can only accept Visitor�s of the same type (type-safe).
- Visitors can have a typed return value, no casting necessary.
Introduction to Generic Class
So let's start by looking at generics and how to make a class generic. I am going to be brief here, since I am hoping that you have a little Generics experience already. We could have lots of articles just explaining generics, but it would be best to assume you have a good understanding of them already and not waste that extra space.
Generics are a way to create a template of your class and allow actual implementations of your template to be type safe. If you were to look at the Javadocs for any of the Collection classes, you would see some interesting characters like E all over the place. The E basically stands for the element type, any type that you will define when you use or extend that class. You can do the same in your classes by just defining the letters that you are going to use.
In our implementation i will try to be more explicit for the generic name than E for Element. I will use Visitor for the Visitor implementation class and Visitable for the visitable node.
Generic visitable interface
First of all, any object that accepts a visitor has a virtual accept method . The accept method is generified to accept only a Generic�Visitor
Generic visitor interface
Here is an implementation of the generic visitor:
Implementing your Generic Visitor interface
Like above we create our GenerifiedVisitor:
Defining a interface for your Visitable Nodes
And our Generic Visitable class:
Conclusion
The capability of Generics to increase type safety is a good thing. Some example don't requires that strict static typing. In many cases, you will have to code a little more, and in many other cases, you will find that you save a lot of coding. Some design patterns really work well with generics and others don't. You are know ready to apply your generic visitor over your Composite visitable tree.
It really is a give and take, trial and error kind of process. The Template Method pattern work extremely well with generics as well. I hope you enjoyed this article.
Comments
Visitors are not suppose to return something. It is common to store the result of your visit in an attribute.
David
All of your methods are void return type.
RSS feed for comments to this post