Mid From PDF GoF Patterns Gang of Four Patterns

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:

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details