Design Pattern Examples
Overview of object-oriented design patterns
Visitor_Exercise.cs
Go to the documentation of this file.
1
5
6using System;
7
9{
26 internal class Visitor_Exercise
27 {
31 // ! [Using Visitor in C#]
32 public void Run()
33 {
34 Console.WriteLine();
35 Console.WriteLine("Visitor Exercise");
36
37 Console.WriteLine(" Creating Village");
38 Village village = new Village();
39 village.LoadVillage();
40
41 OrderVisitor visitor = new OrderVisitor(new string[] { "hamburger" });
42 Console.WriteLine(" Ordering a hamburger from a shop in the {0}", village.Name);
43 // Visit all shops and place an order for a hamburger at the shop
44 // that sells them. We don't know which shop it is and we don't
45 // need to know until we receive the order.
46 village.Accept(visitor);
47 if (visitor.ItemsReceived.Count > 0)
48 {
49 // We are expecting only a single item
50 Console.WriteLine(" We received a {0} from {1}.",
51 visitor.ItemsReceived[0], visitor.ShopNameReceivedFrom);
52 }
53 else
54 {
55 Console.WriteLine(" Failed to receive a hamburger");
56 }
57
58 Console.WriteLine(" Done.");
59 }
60 // ! [Using Visitor in C#]
61
62 }
63}
A visitor used for ordering items from various shops. The user starts with an instance of this class ...
List< string > ItemsReceived
List of items received from an order/pickup process.
string ShopNameReceivedFrom
Name of the shop that provided the item(s).
Represents a collection of shops that can be visited.
void LoadVillage()
Load the village.
string Name
Name of this village.
void Accept(Visitor visitor)
The visitor will call this method on each element it wants to visit.
Example of using the Visitor Pattern in C#.
void Run()
Executes the example for the Visitor Pattern in C#.
The namespace containing all Design Pattern Examples implemented in C#.