Usage (Client Code):?
- The client creates a list of shopping cart elements (books, fruits), and then applies
the visitor (ShoppingCart) to calculate the total cost, which includes applying the
discount to books.
class Program
{
static void Main()
{
var items = new List<IShoppingCartElement>
{
new Book(20),
new Fruit(5)
};
var cart = new ShoppingCart();
foreach (var item in items)
{
item.Accept(cart); // Visitor applies operation
(discount/tax)
}
Console.WriteLine($"Total: {cart.GetTotal()}"); // Total:
24.5 (Book with discount + fruit without discount)
}
}
Output:
Total: 24.5
How the Visitor Pattern Works: