daily-pattern

A series of posts in which I explore (almost) all of the Design Patterns from the Gang of Four's book, using food as a theme.

Command - The Daily Design Pattern

This is part of a series of posts demonstrating software design patterns using C# and .NET. The patterns are taken from the book Design Patterns by the Gang of Four. Here's the series index page.

What Is This Pattern?

The Command design pattern encapsulates a request as an object, thereby allowing us developers to treat that request differently based upon what class receives said command. Further, it enables much more complex architectures, and even enables operations such as undo/redo.

The Chain of Responsibility pattern fits well with the Command pattern, as the former can use objects of the latter to represent its requests.

The Rundown

  • Type: Behavioral
  • Useful? 4/5 (Very)
  • Good For: Encapsulating requests as objects so that they can be processed differently by different receivers.
  • Example Code: On GitHub

The Participants

  • The Command declares an interface for executing an operation.
  • The ConcreteCommand defines a binding between a Receiver and an action.
  • The Client creates a ConcreteCommand object and sets its receiver.
  • The Invoker asks the command to carry out its request.
  • The Receiver knows how to perform the operations associated with carrying out the request.

A Delicious Example

Since just defining the Participants doesn't do a very thorough job of explaining what this pattern is all about, let's build a demo project. In this project, we'll model a system in which we can create an order for a fast food restaurant, and add, remove, and modify items in the order using the Command design pattern.

Several cashiers take orders for a KFC restaurant in Indonesia. Image is KFC Bandung Supermall from Wikimedia, used under license.

To begin building our demo, let's first create a class which represents an item being ordered.

/// <summary>
/// Represents an item being ordered from this restaurant.
/// </summary>
public class MenuItem  
{
    public string Name { get; set; }
    public int Amount { get; set; }
    public double Price { get; set; }

    public MenuItem(string name, int amount, double price)
    {
        Name = name;
        Amount = amount;
        Price = price;
    }

    public void Display()
    {
        Console.WriteLine("\nName: " + Name);
        Console.WriteLine("Amount: " + Amount.ToString());
        Console.WriteLine("Price: $" + Price.ToString());
    }
}

Since those items will be ordered by a patron of the restaurant, let's create a Patron object which will also be our Invoker participant. It just so happens that our implementation of the Invoker also includes a factory method:

/// <summary>
/// The Invoker class
/// </summary>
public class Patron  
{
    private OrderCommand _orderCommand;
    private MenuItem _menuItem;
    private FastFoodOrder _order;

    public Patron()
    {
        _order = new FastFoodOrder();
    }

    public void SetCommand(int commandOption)
    {
        _orderCommand = new CommandFactory().GetCommand(commandOption);
    }

    public void SetMenuItem(MenuItem item)
    {
        _menuItem = item;
    }

    public void ExecuteCommand()
    {
        _order.ExecuteCommand(_orderCommand, _menuItem);
    }

    public void ShowCurrentOrder()
    {
        _order.ShowCurrentItems();
    }
}

public class CommandFactory  
{
    //Factory method
    public OrderCommand GetCommand(int commandOption)
    {
        switch (commandOption)
        {
            case 1:
                return new AddCommand();
            case 2:
                return new ModifyCommand();
            case 3:
                return new RemoveCommand();
            default:
                return new AddCommand();
        }
    }
}

Note that the Patron keeps a reference to an instance of FastFoodOrder, which is our Receiver participant and is implemented like so:

/// <summary>
/// The Receiver
/// </summary>
public class FastFoodOrder  
{
    public List<MenuItem> currentItems { get; set; }
    public FastFoodOrder()
    {
        currentItems = new List<MenuItem>();
    }

    public void ExecuteCommand(OrderCommand command, MenuItem item)
    {
        command.Execute(this.currentItems, item);
    }

    public void ShowCurrentItems()
    {
        foreach(var item in currentItems)
        {
            item.Display();
        }
        Console.WriteLine("-----------------------");
    }
}

FastFoodOrder keeps track of all items in the order, so that when commands arrive at it, it can process those commands using its own list of items.

Speaking of the commands, let's implement the base Command participant:

/// <summary>
/// The Command abstract class
/// </summary>
public abstract class OrderCommand  
{
    public abstract void Execute(List<MenuItem> order, MenuItem newItem);
}

Now we can also implement several ConcreteCommand objects:

/// <summary>
/// A concrete command
/// </summary>
public class AddCommand : OrderCommand  
{
    public override void Execute(List<MenuItem> currentItems, MenuItem newItem)
    {
        currentItems.Add(newItem);
    }
}

/// <summary>
/// A concrete command
/// </summary>
public class RemoveCommand : OrderCommand  
{
    public override void Execute(List<MenuItem> currentItems, MenuItem newItem)
    {
        currentItems.Remove(currentItems.Where(x=>x.Name == newItem.Name).First());
    }
}

/// <summary>
/// A concrete command
/// </summary>
public class ModifyCommand : OrderCommand  
{
    public override void Execute(List<MenuItem> currentItems, MenuItem newItem)
    {
        var item = currentItems.Where(x => x.Name == newItem.Name).First();
        item.Price = newItem.Price;
        item.Amount = newItem.Amount;
    }
}

Now that we've got all the pieces in place, let's create our Client participant which creates a ConcreteCommand and sets the receiver; in this case, let's add several items to our order, then delete an item and change another item.

static void Main(string[] args)  
{
    Patron patron = new Patron();
    patron.SetCommand(1 /*Add*/);
    patron.SetMenuItem(new MenuItem("French Fries", 2, 1.99));
    patron.ExecuteCommand();

    patron.SetCommand(1 /*Add*/);
    patron.SetMenuItem(new MenuItem("Hamburger", 2, 2.59));
    patron.ExecuteCommand();

    patron.SetCommand(1 /*Add*/);
    patron.SetMenuItem(new MenuItem("Drink", 2, 1.19));
    patron.ExecuteCommand();

    patron.ShowCurrentOrder();

    //Remove the french fries
    patron.SetCommand(3 /*Remove*/);
    patron.SetMenuItem(new MenuItem("French Fries", 2, 1.99));
    patron.ExecuteCommand();

    patron.ShowCurrentOrder();

    //Now we want 4 hamburgers rather than 2
    patron.SetCommand(2 /*Edit*/);
    patron.SetMenuItem(new MenuItem("Hamburger", 4, 2.59));
    patron.ExecuteCommand();

    patron.ShowCurrentOrder();

    Console.ReadKey();
}

As the orders are processed by the Receiver (the FastFoodOrder class), the contents of the order changes. Here's the output for this sample project:

A screenshot of the sample project output, showing the changes to the order as commands are submitted.

Will I Ever Use This Pattern?

I have, but you will probably not, unless you are using more complex architectures. In my case, we're building an app using command-query responsibility segregation and event sourcing, two complex architectures which, together, are implementations of the Command design pattern blown up to support large, intricate projects. This is an extremely useful pattern, but invokes a lot of complexity (more so than many other design patterns) so use the Command design pattern with the requisite caution.

Summary

The Command design pattern seeks to encapsulate commands as objects and allow different receivers to process them, according to the receivers' own design.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

Happy Coding! And don't eat too much fast food, now, ya hear?

Get My eBook FREE!

Did you enjoy this post? This article and 21 others are also in my free eBook, "The Daily Design Pattern", which you can get just by signing up for my email list.

Mediator - The Daily Design Pattern

This is part of a series of posts demonstrating software design patterns using C# and .NET. The patterns are taken from the book Design Patterns by the Gang of Four. Here's the series index page.

What Is This Pattern?

The Mediator design pattern defines an object which encapsulates how a set of objects interact with each other.

You can think of a Mediator object as a kind of traffic-coordinator; it directs traffic to appropriate parties based on its own state or outside values. Further, Mediator promotes loose coupling (a good thing!) by keeping objects from referring to each other explicitly.

The Rundown

  • Type: Behavioral
  • Useful? 2/5 (Uncommon)
  • Good For: Defining how objects interact with each other.
  • Example Code: On GitHub

The Participants

  • The Mediator defines an interface for communicating with Collegue objects.
  • The Colleague classes each know what Mediator is responsible for them and communicates with said Mediator whenever it would have otherwise communicated directly with another Colleague.
  • The ConcreteMediator classes implement behavior to coordinate Colleague objects. Each ConcreteMediator knows what its constituent Colleague classes are.

A Delicious Example

To demo the Mediator pattern, let's consider the snack bars in your local movie theatre.

Movie theatres, relative to other kinds of buildings, tend to take up a lot of ground space. A particular cinema that's not too far from me has 25 screens spread out over three different "sections" of the theatre. Each of these sections, being far enough apart from each other, has their own snack bar, from which we gluttonous patrons can order salty snacks and sugary drinks to our increasingly-stressed heart's content.

A concession stand at a movie theatre Image is FineArtsMovieConcessionStand from Wikimedia, used under license

But selling concessions to hungry movie-goers requires supplies, and sometimes the different snack bars might run out of said supplies. Let's imagine a system in which the different concession stands can talk to each other, communicating what supplies they need and who might have them (in short, a chat system for movie snack bars). Let's model this using the Mediator pattern.

First, we'll need our Mediator interface, which defines a method by which the snack bars can talk to each other:

/// <summary>
/// The Mediator interface, which defines a send message method which the concrete mediators must implement.
/// </summary>
interface Mediator  
{
    void SendMessage(string message, ConcessionStand concessionStand);
}

We also need an abstract class to represent the Colleagues that will be talking to one another:

/// <summary>
/// The Colleague abstract class, representing an entity involved in the conversation which should receive messages.
/// </summary>
abstract class ConcessionStand  
{
    protected Mediator mediator;

    public ConcessionStand(Mediator mediator)
    {
        this.mediator = mediator;
    }
}

Now let's implement the different Colleagues. In this case, we'll pretend our movie theatre has two snack bars: one in the northern part of the theatre and one in the southern part.

/// <summary>
/// A Concrete Colleague class
/// </summary>
class NorthConcessionStand : ConcessionStand  
{
    // Constructor
    public NorthConcessionStand(Mediator mediator) : base(mediator)
    {
    }

    public void Send(string message)
    {
        Console.WriteLine("North Concession Stand sends message: " + message);
        mediator.SendMessage(message, this);
    }

    public void Notify(string message)
    {
        Console.WriteLine("North Concession Stand gets message: "  + message);
    }
}

/// <summary>
/// A Concrete Colleague class
/// </summary>
class SouthConcessionStand : ConcessionStand  
{
    public SouthConcessionStand(Mediator mediator) : base(mediator)
    {
    }

    public void Send(string message)
    {
        Console.WriteLine("South Concession Stand sends message: " + message);
        mediator.SendMessage(message, this);
    }

    public void Notify(string message)
    {
        Console.WriteLine("South Concession Stand gets message: " + message);
    }
}

Note that each Colleague must be aware of the Mediator that is mediating the colleague's messages.

Finally, we can implement the ConcreteMediator class, which will keep a reference to each Colleague and manage communication between them.

/// <summary>
/// The Concrete Mediator class, which implement the send message method and keep track of all participants in the conversation.
/// </summary>
class ConcessionsMediator : Mediator  
{
    private NorthConcessionStand _northConcessions;
    private SouthConcessionStand _southConcessions;

    public NorthConcessionStand NorthConcessions
    {
        set { _northConcessions = value; }
    }

    public SouthConcessionStand SouthConcessions
    {
        set { _southConcessions = value; }
    }

    public void SendMessage(string message, ConcessionStand colleague)
    {
        if (colleague == _northConcessions)
        {
            _southConcessions.Notify(message);
        }
        else
        {
            _northConcessions.Notify(message);
        }
    }
}

In our Main(), we can use our newly-written Mediator to simulate a chat conversation between the two snack bars. Suppose that one of the snack bars has run out of popcorn, and needs to know if the other has extra that they're not using:

static void Main(string[] args)  
{
    ConcessionsMediator mediator = new ConcessionsMediator();

    NorthConcessionStand leftKitchen = new NorthConcessionStand(mediator);
    SouthConcessionStand rightKitchen = new SouthConcessionStand(mediator);

    mediator.NorthConcessions = leftKitchen;
    mediator.SouthConcessions = rightKitchen;

    leftKitchen.Send("Can you send some popcorn?");
    rightKitchen.Send("Sure thing, Kenny's on his way.");

    rightKitchen.Send("Do you have any extra hot dogs?  We've had a rush on them over here.");
    leftKitchen.Send("Just a couple, we'll send Kenny back with them.");

    Console.ReadKey();
}

If we run this app, we'll see a conversation between the two concession stands (send/receive messages added to clearly show who sent what):

Will I Ever Use This Pattern?

To be honest, probably not. It's only useful in specific scenarios (e.g. chat systems and the like) and may not be terribly applicable to other types of projects. That said, I'm always open to ideas for using these patterns, so if you've used it in a real-world scenario and want to share with us, please do so in the comments!

Summary

The Mediator pattern encapsulates an object which represents how other objects communicate with one another. By doing so, it enables the Mediator to "stand between" communicating objects and control their communications.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

Happy Coding! And don't forget the popcorn!

Get My eBook FREE!

Did you enjoy this post? This article and 21 others are also in my free eBook, "The Daily Design Pattern", which you can get just by signing up for my email list.

Composite - The Daily Design Pattern

This is part of a series of posts demonstrating software design patterns using C# and .NET. The patterns are taken from the book Design Patterns by the Gang of Four. Here's the series index page.

What Is This Pattern?

The Composite design pattern represents part-whole hierarchies of objects. "Part-whole hierarchies" is a really fancy way of saying you can represent all or part of a hierarchy by reducing the pieces in said hierarchy down to common components.

When using this pattern, clients should be able to treat groups of objects in a hierarchy as "the same" even though they can be different. You can do this selectively to parts of the hierarchy, or to the entire hierarchy.

The Rundown

  • Type: Structural
  • Useful? 4/5 (Very)
  • Good For: Treating different objects in a hierarchy as the same.
  • Example Code: On GitHub

The Participants

  • The Component declares an interface for objects in the composition. It also implements behavior that is common to all objects in said composition. Finally, it must implement an interface for adding/removing it's own child components.
  • The Leaves represent leaf behavior in the composition (a leaf is an object with no children). It also defines primitive behavior for said objects.
  • The Composite defines behavior for components which have children (contrasting the Leaves). It also stores its child components and implements the add/remove children interface from the Component.
  • The Client manipulates objects in the composition through the Component interface.

A Delicious Example

To model Composite effectively, let's think about a soda dispenser. Specifically, one of the Coca-Cola Freestyle machines you'll find at certain restaurants or movie theatres.

A Coca-Cola Freestyle soft drink dispenser.

For those of you that haven't seen these monstrosities, they're not at all like the regular soda dispensers you'll find at restaurants. The regular dispenses have six, or eight, or maybe twelve flavors; the Freestyle machines have potentially hundreds. Any flavor of drink that the Coca-Cola company makes in your part of the world, you can order at this machine.

The most interesting part of this device, though, is its interface. The Freestyle wants you to "drill-down" by first selecting a brand (e.g. Coke, Fanta, Sprite, Dasani, etc.) and then selecting a flavor (e.g. Cherry, Vanilla, etc.). In effect, this creates a hierarchy where "Soda" itself is the root Component; the brands are the child Components, and the flavors are Leaves.

A simplified version of this hierarchy might look like this:

A soft drink decision tree, with three second level nodes for Cola, Lemon-Lime, and Root Beer.  Cola and Root Beer each have two children representing their possible flavors.

Let's model this hierarchy. For all possible flavors of soda that our machine dispenses, we need to know how many calories each particular flavor has. So, in our abstract class that represents all soft drinks, we need a property for Calories:

/// <summary>
/// Soda abstract class
/// </summary>
public abstract class SoftDrink  
{
    public int Calories { get; set; }

    public SoftDrink(int calories)
    {
        Calories = calories;
    }
}

We also need to implement several Leaves for the concrete soda flavors (doesn't that sound disgusting?).

/// <summary>
/// Leaf class
/// </summary>
public class OriginalCola : SoftDrink  
{
    public OriginalCola(int calories) : base(calories) { }
}

/// <summary>
/// Leaf class
/// </summary>
public class CherryCola : SoftDrink  
{
    public CherryCola(int calories) : base(calories) { }
}

/// <summary>
/// Leaf class
/// </summary>
public class OriginalRootBeer : SoftDrink  
{
    public OriginalRootBeer(int calories) : base(calories) { }
}

/// <summary>
/// Leaf class
/// </summary>
public class VanillaRootBeer : SoftDrink  
{
    public VanillaRootBeer(int calories) : base(calories) { }
}

/// <summary>
/// Leaf class
/// </summary>
public class LemonLime : SoftDrink  
{
    public LemonLime(int calories) : base(calories) { }
}

We now need to implement the Composite participant, which represents objects in the hierarchy which have children. For our decision tree, we have two Composites: Colas and RootBeers.

/// <summary>
/// Composite class
/// </summary>
public class Colas  
{
    public List<SoftDrink> AvailableFlavors { get; set; }

    public Colas()
    {
        AvailableFlavors = new List<SoftDrink>();
    }
}

/// <summary>
/// Composite class
/// </summary>
public class RootBeers  
{
    public List<SoftDrink> AvailableFlavors { get; set; }

    public RootBeers()
    {
        AvailableFlavors = new List<SoftDrink>();
    }
}

Now, let's imagine we need to report the amount of calories in each of our flavors to our customers. The customers doesn't care about our hierarchy, they just wants to know how many calories each flavor has. Since we implemented the Composite design pattern, we can provide this data easily in our Component participant (which represents the soda dispenser itself):

/// <summary>
/// The Component class
/// </summary>
public class SodaDispenser  
{
    public Colas Colas { get; set; }
    public LemonLime LemonLime { get; set; }
    public RootBeers RootBeers { get; set; }

    public SodaDispenser()
    {
        Colas = new Colas();
        LemonLime = new LemonLime(190);
        RootBeers = new RootBeers();
    }

    /// <summary>
    /// Returns all available flavors and display their calories
    /// </summary>
    public void DisplayCalories()
    {
        var sodas = new Dictionary<string, int>();
        foreach (var cola in Colas.AvailableFlavors)
        {
            sodas.Add(cola.GetType().Name, cola.Calories);
        }
        sodas.Add(LemonLime.GetType().Name, LemonLime.Calories);

        foreach (var rootbeer in RootBeers.AvailableFlavors)
        {
            sodas.Add(rootbeer.GetType().Name, rootbeer.Calories);
        }

        Console.WriteLine("Calories:");
        foreach (var soda in sodas)
        {
            Console.WriteLine(soda.Key +": " + soda.Value.ToString() + " calories.");
        }
    }
}

Finally, our Main() shows how we might initialize a SodaDispenser with several hierarchical flavors and then display all of the calories for each flavor:

static void Main(string[] args)  
{
    SodaDispenser fountain = new SodaDispenser();
    fountain.Colas.AvailableFlavors.Add(new OriginalCola(220));
    fountain.Colas.AvailableFlavors.Add(new CherryCola(230));
    fountain.LemonLime.Calories = 180;
    fountain.RootBeers.AvailableFlavors.Add(new OriginalRootBeer(225));
    fountain.RootBeers.AvailableFlavors.Add(new VanillaRootBeer(225));
    fountain.DisplayCalories();

    Console.ReadKey();
}

The output of this method being:

A screenshot of the Composite pattern sample project, showing all of the calorie entries for each flavor in the hierarchy.

Will I Ever Use This Pattern?

Will you ever have hierarchical data? If so, probably yes. The key part of this pattern is that you can treat different objects as the same, provided you set up the appropriate interfaces and abstracts.

Summary

The Composite pattern takes objects in a hierarchy and allows clients to treat different parts of that hierarchy as being the same. Then, among other things, you can "flatten" all or part of the hierarchy to get only the data that's common to all of the parts.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

(For all you international soda drinkers out there, maybe you can help me with something. I was not aware that the flavor "root beer" was solely a North American thing, but Wikipedia says it is. Do you all not get this kind of soda in your country? Because it is the bomb and you should try it.)

Happy Coding!

Get My eBook FREE!

Did you enjoy this post? This article and 21 others are also in my free eBook, "The Daily Design Pattern", which you can get just by signing up for my email list.

Visitor - The Daily Design Pattern

This is part of a series of posts demonstrating software design patterns using C# and .NET. The patterns are taken from the book Design Patterns by the Gang of Four. Here's the series index page.

What Is This Pattern?

The Visitor pattern lets us operate on objects by representing that operation as an object unto itself. Thereby, we can operate on said objects without changing the classes or definitions of those objects.

This pattern is particularly useful when, for one reason or another, we cannot modify or refactor existing classes but need to change their behavior.

The Rundown

  • Type: Behavioral
  • Useful? 1/5 (Rarely)
  • Good For: Operating on objects without changing their classes.
  • Example Code: On GitHub

The Participants

  • The Visitor declares an operation for each of ConcreteElement in the object structure.
  • The ConcreteVisitor implements each operation defined by the Visitor. Each operation implements a fragment of the algorithm needed for that object.
  • The Element defines an Accept operation which takes a Visitor as an argument.
  • The ConcreteElement implements the Accept operation defined by the Element.
  • The ObjectStructure can enumerate its elements and may provide a high-level interface to allow the Visitor to visit its elements.

A Delicious Example

To model this pattern, let's talk about a really, really successful restaurant and the employees who work there.

A full curbside restaurant in Shanghai Image is full house at curbside restaurant, found on Flickr and used under license.

In this scenario, our restaurant has been, to put it lightly, killing it. We're full every day, customers rave about our menu, critics love our decor and our staff; in short, we're the best damn restaurant in the city.

Upper management has decided that it's time to reward our hard-working employees by giving them raises and extra time off. Problem is, the classes which represent our employees (stay with me here) are already created and, for whatever reason, cannot be changed.

/// <summary>
/// The Element abstract class.  All this does is define an Accept operation, which needs to be implemented by any class that can be visited.
/// </summary>
abstract class Element  
{
    public abstract void Accept(IVisitor visitor);
}

/// <summary>
/// The ConcreteElement class, which implements all operations defined by the Element.
/// </summary>
class Employee : Element  
{
    public string Name { get; set; }
    public double AnnualSalary { get; set; }
    public int PaidTimeOffDays { get; set; }

    public Employee(string name, double annualSalary, int paidTimeOffDays)
    {
        Name = name;
        AnnualSalary = annualSalary;
        PaidTimeOffDays = paidTimeOffDays;
    }

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

Above are our Element and ConcreteElement participants, representing employees of our restaurant. We need to implement a Visitor which will visit these employee records and modify their salary and paid time off accordingly.

First, let's get our interface IVisitor defined (which is also our Visitor participant):

/// <summary>
/// The Visitor interface, which declares a Visit operation for each ConcreteVisitor to implement.
/// </summary>
interface IVisitor  
{
    void Visit(Element element);
}

Now we need our ConcreteVisitor participants, one for each detail about the employee records that we want to change.

/// <summary>
/// A Concrete Visitor class.
/// </summary>
class IncomeVisitor : IVisitor  
{
    public void Visit(Element element)
    {
        Employee employee = element as Employee;

        // We've had a great year, so 10% pay raises for everyone!
        employee.AnnualSalary *= 1.10;
        Console.WriteLine("{0} {1}'s new income: {2:C}", employee.GetType().Name, employee.Name, employee.AnnualSalary);
    }
}

/// <summary>
/// A Concrete Visitor class
/// </summary>
class PaidTimeOffVisitor : IVisitor  
{
    public void Visit(Element element)
    {
        Employee employee = element as Employee;

        // And because you all helped have such a great year, all my employees get three extra paid time off days each!
        employee.PaidTimeOffDays += 3;
        Console.WriteLine("{0} {1}'s new vacation days: {2}", employee.GetType().Name, employee.Name, employee.PaidTimeOffDays);
    }
}

Finally, we need classes to represent all of our employees as a group and individually. The aggregate collection of employees is our ObjectStructure participant:

/// <summary>
/// The Object Structure class, which is a collection of Concrete Elements.  This could be implemented using another pattern such as Composite.
/// </summary>
class Employees  
{
    private List<Employee> _employees = new List<Employee>();

    public void Attach(Employee employee)
    {
        _employees.Add(employee);
    }

    public void Detach(Employee employee)
    {
        _employees.Remove(employee);
    }

    public void Accept(IVisitor visitor)
    {
        foreach (Employee e in _employees)
        {
            e.Accept(visitor);
        }
        Console.WriteLine();
    }
}


class LineCook : Employee  
{
    public LineCook() : base("Dmitri", 32000, 7)
    {
    }
}

class HeadChef : Employee  
{
    public HeadChef() : base("Jackson", 69015, 21)
    {
    }
}

class GeneralManager : Employee  
{
    public GeneralManager() : base("Amanda", 78000, 24)
    {
    }
}

When we run the app, we will create a new collection of employees and send visitors to modify their salary and paid time off records. It looks like this:

static void Main(string[] args)  
{
    // Who are my employees?
    Employees e = new Employees();
    e.Attach(new LineCook());
    e.Attach(new HeadChef());
    e.Attach(new GeneralManager());

    // Employees are visited, giving them 10% raises and 3 extra paid time off days.
    e.Accept(new IncomeVisitor());
    e.Accept(new PaidTimeOffVisitor());

    Console.ReadKey();
}

Running the sample app produces the following output:

A screenshot of the demo application, showing the increase in both salary and paid time off for the three employees defined.

In short, we created two visitors (IncomeVisitor and PaidTimeOffVisitor) which visited each Employee and modified their internal states before vanishing like a thief in the night. And all of our employees are surely happy with the new money and time we've given them.

Will I Ever Use This Pattern?

Probably not, at least not for simple projects. To be honest, I'm tempted to think of this pattern as being the Burglar pattern rather than the Visitor pattern, since it consists of some heretofore unknown instance of an object showing up, breaking in, rearranging things, and hightailing it out of there.

Further, it appears that more recent versions of C# might actually negate the need to use this pattern in certain scenarios in the first place. Again, I don't have a lot of first-hand experience with this pattern, but if you think it will help you and your projects, might as well give it a go.

Summary

The Visitor pattern allows us to modify existing instances of objects without modifying the class they are a part of. All those instances need to do is accept a Visitor object and process its contents. That said, this pattern (IMO) provides more complexity than value and shouldn't be used extensively.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

Happy Coding!

Get My eBook FREE!

Did you enjoy this post? This article and 21 others are also in my free eBook, "The Daily Design Pattern", which you can get just by signing up for my email list.