implement a visitor pattern for products in csharp

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.cs
public interface IProduct
{
    void Accept(IProductVisitor visitor);
}

public class ProductA : IProduct
{
    public int Quantity { get; set; }

    public void Accept(IProductVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class ProductB : IProduct
{
    public int Weight { get; set; }

    public void Accept(IProductVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public interface IProductVisitor
{
    void Visit(ProductA product);
    void Visit(ProductB product);
}

public class ProductVisitor : IProductVisitor
{
    public void Visit(ProductA product)
    {
        Console.WriteLine($"Processing ProductA with Quantity = {product.Quantity}");
    }

    public void Visit(ProductB product)
    {
        Console.WriteLine($"Processing ProductB with Weight = {product.Weight}");
    }
}
832 chars
44 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.cs
List<IProduct> products = new List<IProduct>();

var productA = new ProductA { Quantity = 10 };
var productB = new ProductB { Weight = 100 };

products.Add(productA);
products.Add(productB);

var productVisitor = new ProductVisitor();

foreach (var product in products)
{
    product.Accept(productVisitor);
}
310 chars
15 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