What is the difference between applying the visitor design pattern to your code and the following approach:
interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
I assume that by using interfaces, we're not really separating the algorithm.
2 Answers. Save this answer. Show activity on this post. The visitor pattern is useful when you want to process a data structure containing different kinds of objects, and you want to perform a specific operation on each of them, depending on its type.
Strategy is based on coding to an interface. Visitor is based on coding to an implementation. Strategy implements one operation in multiple ways. Visitor implements multiple operations.
Advantages and Disadvantages of the Visitor Design PatternNew operations are easy to add without changing element classes (add a new concrete visitor). As a result, different concrete elements don't have to implement their part of a particular algorithm. Related behaviour only focuses on a single concrete visitor.
To make it easy to use for users, we can add a facade which wrap the complexity of the task, and provide one simple interface instead. Same goes for the Facade Design Pattern. It hides the complexities of the system and provides an interface to the client from where the client can access the system.
There is quite a big difference.
The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually "visits" the class and does its thing without the class being modified.
An interface is a basic concept used to provide a common API to a potentially diverse group of classes. The typical test for an interface is that classes that share it are alike in at least that one respect (is-like-a) and in those cases can be treated as such.
Here is a simple example on wikipedia that shows a couple of visitors in java.
Two things:
perfom
and the setInterface
. With a visitor pattern you would only need one method, the perfom
, usually called accept
. setInterface
method- for each. This makes it impossible to make your class immutable.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With