I'm in a class where we just learned about these design patterns. However I couldn't see any difference between them. They sound just like the same, creating concrete classes over the abstract one. Could somebody help me kill this doubt? thanks (:
相关问题
- Name for a method that has only side effects
- What is a correct approach to manage test data usi
- Can a [GoF]-ConcreteSubject override the notify me
- Can the builder pattern ever be doing too much?
- Carry STRef implicitly in an environment during co
Both the visitor, the strategy, and the template pattern encompass the application of an algorithm. The biggest difference is in how they are evoked and how they are used in practice. While it may seem like they have the same use case, look at the construction of the objects to see the difference.
The strategy pattern is often used when we don't have the ability to pass around functions as a first class object. It expects a very specific argument list and only that argument list in its call pattern. For instance:
which is then applied to a list of objects of type "Foo." We really have no other way of applying it to any other object.
The visitor pattern on the other hand is used when we want to apply an algorithm to a bunch of objects that might not share the same signature nor have the same member functions. We say visitor pattern because it's often used when traversing a tree or another collection of "unrelated" objects (unrelated in an inheritance sense.)
Here, the idea is that we'd like to "up" all these objects. They all don't share the same member function signature but all are conceptually related. Hence, we can "visit" each of these classes but expect the algorithm to perform the same type of task.
By using a visitor pattern we avoid the need to wrap each class in a proxy pattern. Hence, for N classes we'd like to apply this algorithm to we don't need to make N proxy classes. We only need to add N methods to a visitor class.
The template method is quite different from either the visitor and the strategy pattern. With the template what you're trying to do is enforce the same type of algorithm but on different subclasses within a hierarchy. For instance:
So the result of the algorithm varies within the heirarchy.
Commonalities:
Differences:
Have a look at Template method , Strategy and Visitor and Sourcemaking articles for better understanding.
Related posts:
When should I use the Visitor Design Pattern?
Real World Example of the Strategy Pattern
Template design pattern in JDK, could not find a method defining set of methods to be executed in order