creational-patterns

Software design patterns which deal with the creation of objects and instances of those objects.

Builder - 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 Builder pattern separates the construction of an object from its representation so that the same construction process can create different representations.

The general idea is that the order in which things happen when an object is instantiated will be the same, but the actual details of those steps change based upon what the concrete implementation is.

The Rundown

  • Type: Creational
  • Useful?: 1.5/5 (Almost certainly not)
  • Good For: Creating objects which need several steps to happen in order, but the steps are different for different specific implementations.
  • Example Code: On GitHub

The Participants

  • The Builder specifies an abstract interface for creating parts of a Product.
  • The ConcreteBuilder constructs and assembles parts of the product by implementing the Builder interface. It must also define and track the representation it creates.
  • The Product represents the object being constructed. It includes classes for defining the parts of the object, including any interfaces for assembling the parts into the final result.
  • The Director constructs an object using the Builder interface.

A Delicious Example

To demonstrate how the Builder design pattern works, we once again turn our hungry eyes to that most portable and simple of lunch foods: the humble sandwich.

A turkey sandwich, served at a deli.

Here's the thing about sandwiches: the only thing that defines a sandwich is something edible between two slices of bread. That's it. This means that a hot dog is a sandwich, which seems like a ridiculous statement but is technically correct (and technically correct is the best kind of correct).

That said, different types of sandwiches require different steps in order to make them, but they're still just sandwiches. Most of the time, the same kinds of ingredients will be used to create many different kinds of sandwiches. Let's see how we can use the Builder pattern to build us some of these yummy sandwiches.

To start off, we need tom implement the Director participant. We'll call our Director AssemblyLine, make it a class, and it will define in what steps the process of making a sandwich are called.

/// <summary>
/// The Director
/// </summary>
class AssemblyLine  
{
    // Builder uses a complex series of steps
    // 
    public void Assemble(SandwichBuilder sandwichBuilder)
    {
        sandwichBuilder.AddBread();
        sandwichBuilder.AddMeats();
        sandwichBuilder.AddCheese();
        sandwichBuilder.AddVeggies();
        sandwichBuilder.AddCondiments();
    }
}

We also need to define the Product participant which is being built by the Builder participant. For this demo, the Product is, of course, a Sandwich.

/// <summary>
/// The Product class
/// </summary>
class Sandwich  
{
    private string _sandwichType;
    private Dictionary<string, string> _ingredients = new Dictionary<string, string>();

    // Constructor
    public Sandwich(string sandwichType)
    {
        this._sandwichType = sandwichType;
    }

    // Indexer
    public string this[string key]
    {
        get { return _ingredients[key]; }
        set { _ingredients[key] = value; }
    }

    public void Show()
    {
        Console.WriteLine("\n---------------------------");
        Console.WriteLine("Sandwich: {0}", _sandwichType);
        Console.WriteLine(" Bread: {0}", _ingredients["bread"]);
        Console.WriteLine(" Meat: {0}", _ingredients["meat"]);
        Console.WriteLine(" Cheese: {0}", _ingredients["cheese"]);
        Console.WriteLine(" Veggies: {0}", _ingredients["veggies"]);
        Console.WriteLine(" Condiments: {0}", _ingredients["condiments"]);
    }
}

Now that we know the definition of the product we are building, let's now create the Builder participant - an abstract class SandwichBuilder:

/// <summary>
/// The Builder abstract class
/// </summary>
abstract class SandwichBuilder  
{
    protected Sandwich sandwich;

    // Gets sandwich instance
    public Sandwich Sandwich
    {
        get { return sandwich; }
    }

    // Abstract build methods
    public abstract void AddBread();
    public abstract void AddMeats();
    public abstract void AddCheese();
    public abstract void AddVeggies();
    public abstract void AddCondiments();
}

Notice the five abstract methods. Each subclass of SandwichBuilder will need to implement those methods in order to properly build a sandwich.

Next, let's implement a few ConcreteBuilder classes to build some specific sandwiches.

/// <summary>
/// A ConcreteBuilder class
/// </summary>
class TurkeyClub : SandwichBuilder  
{
    public TurkeyClub()
    {
        sandwich = new Sandwich("Turkey Club");
    }

    public override void AddBread()
    {
        sandwich["bread"] = "12-Grain";
    }

    public override void AddMeats()
    {
        sandwich["meat"] = "Turkey";
    }

    public override void AddCheese()
    {
        sandwich["cheese"] = "Swiss";
    }

    public override void AddVeggies()
    {
        sandwich["veggies"] = "Lettuce, Tomato";
    }

    public override void AddCondiments()
    {
        sandwich["condiments"] = "Mayo";
    }
}


/// <summary>
/// A ConcreteBuilder class
/// </summary>
class BLT : SandwichBuilder  
{
    public BLT()
    {
        sandwich = new Sandwich("BLT");
    }

    public override void AddBread()
    {
        sandwich["bread"] = "Wheat";
    }

    public override void AddMeats()
    {
        sandwich["meat"] = "Bacon";
    }

    public override void AddCheese()
    {
        sandwich["cheese"] = "None";
    }

    public override void AddVeggies()
    {
        sandwich["veggies"] = "Lettuce, Tomato";
    }

    public override void AddCondiments()
    {
        sandwich["condiments"] = "Mayo, Mustard";
    }
}

/// <summary>
/// A ConcreteBuilder class
/// </summary>
class HamAndCheese : SandwichBuilder  
{
    public HamAndCheese()
    {
        sandwich = new Sandwich("Ham and Cheese");
    }

    public override void AddBread()
    {
        sandwich["bread"] = "White";
    }

    public override void AddMeats()
    {
        sandwich["meat"] = "Ham";
    }

    public override void AddCheese()
    {
        sandwich["cheese"] = "American";
    }

    public override void AddVeggies()
    {
        sandwich["veggies"] = "None";
    }

    public override void AddCondiments()
    {
        sandwich["condiments"] = "Mayo";
    }
}

Once we have all the ConcreteBuilder classes written up, we can use them in our Main() like so:

static void Main(string[] args)  
{
    SandwichBuilder builder;

    // Create shop with sandwich assembly line
    AssemblyLine shop = new AssemblyLine();

    // Construct and display sandwiches
    builder = new HamAndCheese();
    shop.Assemble(builder);
    builder.Sandwich.Show();

    builder = new BLT();
    shop.Assemble(builder);
    builder.Sandwich.Show();

    builder = new TurkeyClub();
    shop.Assemble(builder);
    builder.Sandwich.Show();

    // Wait for user
    Console.ReadKey();
}

The nice thing about this pattern is that we can now reuse the AssemblyLine class on any SandwichBuilder we wish, and we have more fine-grained control over how the sandwiches are built.

(Yes, that pun was intentional. No, I'm not sorry.)

Will I Ever Use This Pattern?

Probably not. Let's face it, this is a lot of work to build these supposedly related items in a reusable manner. The patterns some degree of assumptions about how these objects should be created, and for me it's too many assumptions to rely on using this pattern in common projects. Seems to me like the Builder pattern has some uses, just not a lot of them.

Summary

The Builder pattern allows us to build related sets of objects with the same steps, but leaving the implementation of those steps up to the subclasses. It's not terribly useful as far as I can see, but if someone out there has a good use for it I'd love to hear about it in the comments.

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.

Singleton - 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?

Singleton is a Creational design pattern in which a class is guaranteed to only ever have exactly one instance, with that instance being globally accessible.

What this means is that the pattern forces a particular object to not have an accessible constructor, and that any access performed on the object is performed upon the same instance of that object.

As you may have heard, Singleton is one of the most maligned design patterns (for reasons we will discuss below).

The Rundown

The Participants

Kinda silly to define participants for this particular design pattern, but here you go:

  • The Singleton is a class which defines exactly one instance of itself, and that instance is globally accessible.

A Delicious Example

The theme I've been using for the Daily Pattern series so far is "food", but food items are not a good way to model Singleton: there's not ever going to be a piece of food that everybody will access a single instance of (because that would be gross). Instead, let's visit our local diner and think about that little bell that sits on the counter.

A coffee mug, bell, and receipt stick with receipts sit on a wooden countertop.

In movies, one of the best ways to identify that the characters are in a greasy diner(warning: TVTropes link) is by having an overweight chef with a dirty apron hit a bell and yell "Order Up!". The thing about that bell is that there's probably only ever one; the sound is used to notify the servers that the next order is at the window and needs to be taken to the tables.

If there's only ever one, we can model that as a Singleton.

/// <summary>
/// Singleton
/// </summary>
public sealed class TheBell  
{
    private static TheBell bellConnection;
    private static object syncRoot = new Object();
    private TheBell()
    {

    }

    /// <summary>
    /// We implement this method to ensure thread safety for our singleton.
    /// </summary>
    public static TheBell Instance
    {
        get
        {
            lock(syncRoot)
            {
                if(bellConnection == null)
                {
                    bellConnection = new TheBell();
                }
            }

            return bellConnection;
        }
    }

    public void Ring()
    {
        Console.WriteLine("Ding! Order up!");
    }
}

Notice that the TheBell class has a private constructor. This is to ensure that it can never be instantiated, and can only be accessed through the Instance property.

Further, note the syncRoot object. This a simple object that allows our Singleton to be thread-safe; since there's only ever one, we must ensure that any thread which wants to access it has an exclusive lock on it.

This Pattern Has Problems

Singleton is probably the most maligned Design Pattern, and for good reason.

For one thing, Singletons are not global variables, though the latter is often mistaken for the former. A Singleton is a class unto itself, and global variables are just properties.

Further, many people argue that Singletons violate common guiding principles such as the Single Responsibility Principle. By its very nature, you cannot pass a Singleton to other classes, and this is often a code smell.

Mostly, though, Singletons are maligned because they are so often misused. It's entirely too easy, to paraphrase Jamie Zawinski, to see a problem, think "I know, I'll use a Singleton," and end up with two problems. Be careful that what you're using the Singleton for actually requires that pattern, and even then be on the lookout for a better, more appropriate manner by which you can solve your current problem.

Will I Ever Use This Pattern?

Not on purpose.

(Kidding, kidding. Sort of.)

Thing is, Singletons are (fittingly) good for one and only one purpose yet are easily understood and quick to implement, which makes them a favorite of people afflicted with golden hammer syndrome. It's all too common to find Singletons in use where global variables should be used instead.

Use the Singleton design pattern sparingly and only for its intended purpose (a single, globally accessible instance of an object) with full knowledge of this pattern's limits, and you'll find that it, like all the other design patterns, has its own set of valid uses.

Summary

Singletons are objects of which there can only ever be exactly one instance. They're not global variables and many people think they violate common principles of good software development, but they do have their uses and so should be used sparingly.

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.

DING! Order Up! (aka 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.

Prototype - 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?

Prototype is a Creational design pattern in which objects are created using a prototypical instance of said object. This pattern is particularly useful for creating lots of instances of an object, all of which share some or all of their values.

The typical way of thinking about this pattern is to consider how we might model the color spectrum. There are something like 10 million visible colors, so modeling them as individual classes (e.g. Red, LightMauve, MacaroniAndCheese, NotYellowButNotGreenEither) would be rather impractical.

However, a color is a color, no matter what color it is; colors have the same kinds of properties as each other even if they don't have the same values for those properties. If we needed to create a lot of color instances, we could do so using the Prototype design pattern.

The Rundown

  • Type: Creational
  • Useful? 3/5 (Sometimes)
  • Good For: Creating lots of similar objects.
  • Example Code: On GitHub

The Participants

  • The Prototype declares an interface for cloning itself.
  • The ConcretePrototype implements the cloning operation defined in the Prototype.
  • The Client creates a new object by asking the Prototype to clone itself.

A Delicious Example

To demo this pattern, let's think about sandwiches (like we did for Factory Method and Abstract Factory).

A variety of grilled sandwiches, sitting on a countertop

(As you can probably tell, I like sandwiches).

In the picture above, there are many kinds of sandwiches. Just like the color example above, a sandwich is still a sandwich no matter what's between the two slices of bread. Let's demo how we can use the Prototype pattern to build lots of sandwiches.

First, we'll create an abstract class (the Prototype participant) to represent a sandwich, and define a method by which the abstract Sandwich class can clone itself:

/// <summary>
/// The Prototype abstract class
/// </summary>
abstract class SandwichPrototype  
{
    public abstract SandwichPrototype Clone();
}

Now we need the ConcretePrototype participant class that can clone itself to create more Sandwich instances. For our model, we'll say that a Sandwich consists of four parts: the meat, cheese, bread, and veggies. Here's that class:

class Sandwich : SandwichPrototype  
{
    private string Bread;
    private string Meat;
    private string Cheese;
    private string Veggies;

    public Sandwich(string bread, string meat, string cheese, string veggies)
    {
        Bread = bread;
        Meat = meat;
        Cheese = cheese;
        Veggies = veggies;
    }

    public override SandwichPrototype Clone()
    {
        string ingredientList = GetIngredientList();
        Console.WriteLine("Cloning sandwich with ingredients: {0}", ingredientList.Remove(ingredientList.LastIndexOf(",")));

        return MemberwiseClone() as SandwichPrototype;
    }

    private string GetIngredientList()
    {
        ...
    }
}

class SandwichMenu  
{
    private Dictionary<string, SandwichPrototype> _sandwiches = new Dictionary<string, SandwichPrototype>();

    public SandwichPrototype this[string name]
    {
        get { return _sandwiches[name]; }
        set { _sandwiches.Add(name, value); }
    }
}

Now we need to create a bunch of sandwiches. In our Main() method (which does double-duty as our Client participant), we can do just that by instantiating the prototype and then cloning it, thereby populating our ``SandwichMenu```:

class Program  
{
    static void Main(string[] args)
    {
        SandwichMenu sandwichMenu = new SandwichMenu();

        // Initialize with default sandwiches
        sandwichMenu["BLT"] = new Sandwich("Wheat", "Bacon", "", "Lettuce, Tomato");
        sandwichMenu["PB&J"] = new Sandwich("White", "", "", "Peanut Butter, Jelly");
        sandwichMenu["Turkey"] = new Sandwich("Rye", "Turkey", "Swiss", "Lettuce, Onion, Tomato");

        // Deli manager adds custom sandwiches
        sandwichMenu["LoadedBLT"] = new Sandwich("Wheat", "Turkey, Bacon", "American", "Lettuce, Tomato, Onion, Olives");
        sandwichMenu["ThreeMeatCombo"] = new Sandwich("Rye", "Turkey, Ham, Salami", "Provolone", "Lettuce, Onion");
        sandwichMenu["Vegetarian"] = new Sandwich("Wheat", "", "", "Lettuce, Onion, Tomato, Olives, Spinach");

        // Now we can clone these sandwiches
        Sandwich sandwich1 = sandwichMenu["BLT"].Clone() as Sandwich;
        Sandwich sandwich2 = sandwichMenu["ThreeMeatCombo"].Clone() as Sandwich;
        Sandwich sandwich3 = sandwichMenu["Vegetarian"].Clone() as Sandwich;

        // Wait for user
        Console.ReadKey();
    }
}

By the time we get to the line Console.ReadKey(), how many total separate instances of Sandwich do we have? Nine, six in the sandwichMenu and three initialized as variables sandwich1, sandwich2, sandwich3.

Will I Ever Use This Pattern?

Possibly. It's a good idea if you have the scenario described above. However, I'm not sure how common that scenario is in regular day-to-day coding; I haven't (consciously) implemented this pattern in several years.

The situation in which I see this pattern as being the most useful is when all of the following happens:

  1. You need to create a lot of instances of an object,
  2. AND those instances will be the same or similar as the prototypical instance.
  3. AND creating a new instance of this object would be markedly slower than cloning an existing instance.

If you have all of those conditions, the Prototype design pattern is for you!

Summary

The Prototype pattern initializes objects by cloning them from a prototypical instance of said object. It's especially useful when you need to create many instances of related items, each of which could be slightly (but not very) different from the other instances. The primary benefit of this pattern is reduced initialization costs; by cloning many instances from a prototypical instance, you theoretically improve performance.

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.

Abstract Factory - 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 Abstract Factory Pattern (AKA Factory of Factories) is a Creational pattern in which interfaces are defined for creating families of related objects without specifying their actual implementations.

When using this pattern, you create factories which return many kinds of related objects. This pattern enables larger architectures such as Dependency Injection.

The Rundown

  • Type: Creational
  • Useful?: 5/5 (Extremely)
  • Good For: Creating objects in different related families without relying on concrete implementations.
  • Example Code: On GitHub

The Participants

  • The AbstractFactory declares an interface for operations which will create AbstractProduct objects.
  • The ConcreteFactory objects implement the operations defined by the AbstractFactory.
  • The AbstractProduct declares an interface for a type of product.
  • The Products define a product object that will be created by the corresponding ConcreteFactory.
  • The Client uses the AbstractFactory and AbstractProduct interfaces.

A Delicious Example

When we modeled the Factory Method pattern, we did so using sandwiches. The thing about sandwiches is that they no matter what they are made of (turkey, roast beef, veggies, peanut butter and jelly) they're still sandwiches, e.g. something edible between two slices of bread. In that example, sandwiches could be considered a family of related objects. But what if wanted to model several families of objects, not just one?

For this demo, let's go more general and model entire sets of recipes.

A cookbook, laying on a table, open to a particular recipe

Let's say we want to model two kinds of recipes: a Sandwich and a Dessert. Further, let's make the assumption that adults and kids don't eat the same things, and so we want one of each kind of recipe for adults and children.

To demo this, let's make some abstract classes representing the generic kinds of recipes (these are our AbstractProduct participants):

/// <summary>
/// An abstract object.
/// </summary>
abstract class Sandwich { }

/// <summary>
/// An abstract object.
/// </summary>
abstract class Dessert { }  

Next, we need an abstract class that will return a Sandwich and a Dessert (this is the AbstractFactory participant):

/// <summary>
/// The AbstractFactory class, which defines methods for creating abstract objects.
/// </summary>
abstract class RecipeFactory  
{
    public abstract Sandwich CreateSandwich();
    public abstract Dessert CreateDessert();
}

Now we can start implementing the actual objects. First let's consider the adult menu (these next classes are ConcreteProduct objects):

/// <summary>
/// A ConcreteProduct
/// </summary>
class BLT : Sandwich { }

/// <summary>
/// A ConcreteProduct
/// </summary>
class CremeBrulee : Dessert { }  

We also need a ConcreteFactory which implements the AbstractFactory and returns the adult recipes:

/// <summary>
/// A ConcreteFactory which creates concrete objects by implementing the abstract factory's methods.
/// </summary>
class AdultCuisineFactory : RecipeFactory  
{
    public override Sandwich CreateSandwich()
    {
        return new BLT();
    }

    public override Dessert CreateDessert()
    {
        return new CremeBrulee();
    }
}

Now let's define the Child's recipes. Here are the ConcreteProduct classes and ConcreteFactory for said recipes:

/// <summary>
/// A concrete object
/// </summary>
class GrilledCheese : Sandwich { }

/// <summary>
/// A concrete object
/// </summary>
class IceCreamSundae : Dessert { }

/// <summary>
/// A concrete factory which creates concrete objects by implementing the abstract factory's methods.
/// </summary>
class KidCuisineFactory : RecipeFactory  
{
    public override Sandwich CreateSandwich()
    {
        return new GrilledCheese();
    }

    public override Dessert CreateDessert()
    {
        return new IceCreamSundae();
    }
}

How do we use this? First, let's ask the user if they are an adult or a child, then display the corresponding menu items.

class Program  
{
    static void Main(string[] args)
    {
        Console.WriteLine("Who are you? (A)dult or (C)hild?");
        char input = Console.ReadKey().KeyChar;
        RecipeFactory factory;
        switch(input)
        {
            case 'A':
                factory = new AdultCuisineFactory();
                break;

            case 'C':
                factory = new KidCuisineFactory();
                break;

            default:
                throw new NotImplementedException();

        }

        var sandwich = factory.CreateSandwich();
        var dessert = factory.CreateDessert();

        Console.WriteLine("\nSandwich: " + sandwich.GetType().Name);
        Console.WriteLine("Dessert: " + dessert.GetType().Name);

        Console.ReadKey();
    }
}

When we run the app, the output looks something like this:

A screenshot of the running app, showing the Adult selections of BLT and Creme Brulee

A screenshot of the running app, showing the Child selections of Grilled Cheese and Ice Cream Sundae

Will I Ever Use This Pattern?

Unquestionably. Abstract Factory is an extremely common pattern, and as mentioned earlier it enables architectures such as Dependency Injection. That said, it's also one of the patterns that's prone to overuse: it's easy to start using Abstract Factories anytime you need to create objects. Be aware of when you decide to use this pattern, and make sure you actually need it.

Summary

The Abstract Factory pattern allows us to generically define families of related objects, leaving the actual concretions for those objects to be implemented as needed.

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.