The Visitor pattern is a behavioral design pattern that allows you to separate the algorithms that operate on a complex object structure from the objects themselves. In this case, the product catalog could be considered the complex object structure.
Here's an example implementation of a visitor pattern for products in C#:
main.cs832 chars44 lines
In this implementation, there is an IProduct
interface that defines an Accept
method. This method takes an IProductVisitor
as a parameter and allows the visitor to perform operations on the product.
ProductA
and ProductB
are concrete implementations of IProduct
.
IProductVisitor
is the visitor interface that declares the Visit
methods for each concrete product type.
ProductVisitor
is a concrete implementation of IProductVisitor
that implements the Visit
methods for ProductA and ProductB.
Here's how you would use this pattern:
main.cs310 chars15 lines
In this example, a collection of products is created and added to. The ProductVisitor
is created and then used to iterate over each product, calling the Accept
method on each one. The Accept
method then calls the appropriate Visit
method on the visitor.
gistlibby LogSnag