structural-patterns

Design patterns which are concerned with the structure of code and objects. They generally try to ease relationships between objects by identifying simpler methods of relating them.

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.

Decorator - 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 Decorator design pattern seeks to add new functionality to an existing object without changing that object's definition.

In other words, it wants to add new responsibilities to an individual instance of an object, without adding those responsibilities to the class of objects. Decorator can be thought of as an alternative to inheritance.

The Rundown

  • Type: Structural
  • Useful? 3/5 (Sometimes)
  • Good For: Injecting new functionality into instances of objects at runtime rather than including that functionality in the class of objects.
  • Example Code: On GitHub

The Participants

  • The Component defines the interface for objects which will have responsibilities or abilities added to them dynamically.
  • The ConcreteComponent objects are objects to which said responsibilities are added.
  • The Decorator maintains a reference to a Component and defines and interface that conforms to the Component interface.
  • The ConcreteDecorator objects are the classes which actually add responsibilities to the ConcreteComponent classes.

A Delicious Example

To demonstrate how we might use the Decorator design pattern, let's imagine that we run a farm-to-table restaurant.

A set of tables at an outdoor restaurant, ready for the lunch rush.

The idea of our restaurant is that we only make dishes from ingredients that are available from our farm; that is, we can only make things from the crops that we grow. Further, sometimes we get a rush on particular dishes, and when this happens we occasionally need to stop selling particular dishes until we can harvest more ingredients (after all, veggies don't grow overnight). In this case, then, we need to be able to mark certain dishes as "sold out" once we run out of ingredients.

To model this, let's first define our Component participant, which is our abstract RestaurantDish class:

/// <summary>
/// The abstract Component class
/// </summary>
abstract class RestaurantDish  
{
    public abstract void Display();
}

We also need a couple ConcreteComponent participant classes representing the individual dishes we serve. These classes only implement their properties, not the number of dishes available (which is the responsibility of the Decorator).

/// <summary>
/// A ConcreteComponent class
/// </summary>
class FreshSalad : RestaurantDish  
{
    private string _greens;
    private string _cheese; //I am going to use this pun everywhere I can
    private string _dressing;

    public FreshSalad(string greens, string cheese, string dressing)
    {
        _greens = greens;
        _cheese = cheese;
        _dressing = dressing;
    }

    public override void Display()
    {
        Console.WriteLine("\nFresh Salad:");
        Console.WriteLine(" Greens: {0}", _greens);
        Console.WriteLine(" Cheese: {0}", _cheese);
        Console.WriteLine(" Dressing: {0}", _dressing);
    }
}

/// <summary>
/// A ConcreteComponent class
/// </summary>
class Pasta : RestaurantDish  
{
    private string _pastaType;
    private string _sauce;

    public Pasta(string pastaType, string sauce)
    {
        _pastaType = pastaType;
        _sauce = sauce;
    }

    public override void Display()
    {
        Console.WriteLine("\nClassic Pasta:");
        Console.WriteLine(" Pasta: {0}", _pastaType);
        Console.WriteLine(" Sauce: {0}", _sauce);
    }
}

We need to decorate those dishes at runtime with the ability to keep track of whether or not we've exhausted all the ingredients. To do this, let's first implement a Decorator abstract class (which, in a rare case of name matching purpose, is also our Decorator participant):

/// <summary>
/// The abstract Decorator class.  
/// </summary>
abstract class Decorator : RestaurantDish  
{
    protected RestaurantDish _dish;

    public Decorator(RestaurantDish dish)
    {
        _dish = dish;
    }

    public override void Display()
    {
        _dish.Display();
    }
}

Finally, we need a ConcreteDecorator for keeping track of how many of the dishes have been ordered.

/// <summary>
/// A ConcreteDecorator. This class will impart "responsibilities" onto the dishes 
/// (e.g. whether or not those dishes have enough ingredients left to order them)
/// </summary>
class Available : Decorator  
{
    public int NumAvailable { get; set; } //How many can we make?
    protected List<string> customers = new List<string>();
    public Available(RestaurantDish dish, int numAvailable) : base(dish)
    {
            NumAvailable = numAvailable;
    }

    public void OrderItem(string name)
    {
        if (NumAvailable > 0)
        {
            customers.Add(name);
            NumAvailable--;
        }
        else
        {
            Console.WriteLine("\nNot enough ingredients for " + name + "'s order!");
        }
    }

    public override void Display()
    {
        base.Display();

        foreach(var customer in customers)
        {
            Console.WriteLine("Ordered by " + customer);
        }
    }
}

Like many of the other patterns, all of this setup comes to fruition in the Main(). First, we define a set of dishes, then we decorate those dishes so that when we run out of ingredients we can notify the patron. Finally, we order those dishes. The complete main method looks like this:

static void Main(string[] args)  
{
    //Step 1: Define some dishes, and how many of each we can make
    FreshSalad caesarSalad = new FreshSalad("Crisp romaine lettuce", "Freshly-grated Parmesan cheese", "House-made Caesar dressing");
    caesarSalad.Display();

    Pasta fettuccineAlfredo = new Pasta("Fresh-made daily pasta", "Creamly garlic alfredo sauce");
    fettuccineAlfredo.Display();

    Console.WriteLine("\nMaking these dishes available.");

    //Step 2: Decorate the dishes; now if we attempt to order them once we're out of ingredients, we can notify the customer
    Available caesarAvailable = new Available(caesarSalad, 3);
    Available alfredoAvailable = new Available(fettuccineAlfredo, 4);

    //Step 3: Order a bunch of dishes
    caesarAvailable.OrderItem("John");
    caesarAvailable.OrderItem("Sally");
    caesarAvailable.OrderItem("Manush");

    alfredoAvailable.OrderItem("Sally");
    alfredoAvailable.OrderItem("Francis");
    alfredoAvailable.OrderItem("Venkat");
    alfredoAvailable.OrderItem("Diana");
    alfredoAvailable.OrderItem("Dennis"); //There won't be enough for this order.

    caesarAvailable.Display();
    alfredoAvailable.Display();

    Console.ReadKey();
}

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

A screenshot of the sample app in action, showing two dishes ordered, one of which was ordered too many times.

As you can see, Dennis can't order the fettuccine alfredo because we've run out of ingredients.

Will I Ever Use This Pattern?

Maybe? I haven't personally used it outside of demos, but I can see it being useful in many circumstances. I'm also wondering if maybe ASP.NET MVC's attributes count as usage of the Decorator pattern, but I'm not sure (so if anyone can clear this up for me, I'd be much obliged).

Summary

The Decorator pattern seeks to dynamically add functionality to instances of objects at runtime, without needing to change the definition of the instance's class. This is especially useful in scenarios where different instances of the same object might behave differently (such as dishes in a restaurant or items in a library).

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.

Man, all this food is making me hungry. Where'd that caesar salad I had go?

A caesar salad with dressing

Ah, found it! 'Scuse me whilst I eat my lunch.

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.

Proxy - 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 Proxy pattern provides a surrogate or placeholder object to control access to another, different object. The Proxy object can be used in the same manner as its containing object.

The Proxy object can then hide or change data on the hidden object, or otherwise manipulate its behavior. However, the Proxy must still be able to be used anywhere the hidden object is.

The Rundown

  • Type: Structural
  • Useful? 4/5 (Very)
  • Good For: Controlling access to a particular object, testing scenarios.
  • Example Code: On GitHub

The Participants

  • The Subject defines a common interface for the RealSubject and the Proxy such that the Proxy can be used anywhere the RealSubject is expected.
  • The RealSubject defines the concrete object which the Proxy represents.
  • The Proxy maintains a reference to the RealSubject and controls access to it. It must implement the same interface as the RealSubject so that the two can be used interchangeably.

A Delicious Example

To demonstrate how to use the Proxy design pattern in real-world code, let's talk about servers in a high-end restaurant (as we did for Facade and for Adapter).

A waiter at a hotel restaurant shows the daily menu

For this demo, let's imagine that servers at a restaurant primarily do three things:

  1. Take the patron's order.
  2. Deliver the patron's order.
  3. Process the diner's payment.

With these assumptions, we can create an interface for these actions (this interface being the Subject participant):

/// <summary>
/// The Subject interface which both the RealSubject and proxy will need to implement
/// </summary>
public interface IServer  
{
    void TakeOrder(string order);
    string DeliverOrder();
    void ProcessPayment(string payment);
}

Now let's create a real Server class (the RealSubject participant):

/// <summary>
/// The RealSubject class which the Proxy can stand in for
/// </summary>
class Server : IServer  
{
    private string Order;
    public void TakeOrder(string order)
    {
        Console.WriteLine("Server takes order for " + order + ".");
        Order = order;
    }

    public string DeliverOrder()
    {
        return Order;
    }

    public void ProcessPayment(string payment)
    {
        Console.WriteLine("Payment for order (" + payment + ") processed.");
    }
}

Now imagine for a second that our Server instance is an experienced server who is helping train a newly-employed server. That new employee, from the patron's perspective, is still a server and will still behave as such. However, the new trainee cannot process payments yet, as he must first learn the ropes of taking and delivering orders.

We can create a Proxy to model this new employee. The Proxy will need to maintain a reference back to the Server instance so that it can call the Server instance's ProcessPayment() method:

/// <summary>
/// The Proxy class, which can substitute for the Real Subject.
/// </summary>
class NewServerProxy : IServer  
{
    private string Order;
    private Server _server = new Server();

    public void TakeOrder(string order)
    {
        Console.WriteLine("New trainee server takes order for " + order + ".");
        Order = order;
    }

    public string DeliverOrder()
    {
        return Order;
    }

    public void ProcessPayment(string payment)
    {
        Console.WriteLine("New trainee cannot process payments yet!")
        _server.ProcessPayment(payment);
    }
}

As you can see, the NewServerProxy implements its own TakeOrder() and DeliverOrder() methods, and calls the Server class's ProcessPayment() method. Since they both implement IServer, the NewServerProxy can be used any place the Server can be used.

Will I Ever Use This Pattern?

Probably. If you've ever had a need to change the behavior of an existing object without actually changing the definition of that object, the Proxy pattern can allow you to do that. Further, I can see this being very useful in testing scenarios, where you might need to replicate a class's behavior without fully implementing it.

Summary

The Proxy pattern seeks to create a "stand-in" object which can be used in place of an existing object and maintains a reference to an instance of said existing object. To fulfill the pattern, the Proxy object must be able to be used anywhere the replaced object can be used.

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.

And, while you're here, check out our wine specials. There's sure to be something to suit your taste.

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.

Flyweight - 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 Flyweight design pattern is used to create lots of small, related objects without invoking a lot of overhead work in doing so, thereby improving performance and maintainability.

The idea is that each Flyweight object has two pieces:

  1. The intrinsic state, which is stored within the Flyweight object itself, and
  2. The extrinsic state, which is stored or calculated by other components.

The Flyweight design pattern allows many instances of an object to share their intrinsic state and thereby reduce the cost associated with creating them.

The Rundown

  • Type: Structural
  • Useful? 1/5 (Nope)
  • Good For: Creating lots of instances of the same set of objects and thereby improving performance.
  • Example Code: On GitHub

The Participants

  • The Flyweight declares an interface through which flyweights can receive and act upon extrinsic state.
  • The ConcreteFlyweight objects implement the Flyweight interface and may be sharable. Any state stored by these objects must be intrinsic to the object.
  • The FlyweightFactory creates and manages flyweight objects, while also ensuring that they are shared properly. When the FlyweightFactory is asked to create an object, it either uses an existing instance of that object or creates a new one if no existing one exists.
  • The Client maintains a reference to flyweights and computes or stores the extrinsic state of said flyweights.

A Delicious Example

To model the Flyweight pattern, let's think about sliders.

A selection of sliders, served on a party tray. A party tray of sliders at a restaurant from Wikimedia, used under license

For those of you who might not be familiar with the term "slider" when it relates to hamburgers, a slider is a small burger, typically only 3 or 4 inches in diameter. They're often used as party snacks, but can also be a meal unto themselves.

At any rate, let's imagine that we need to create a whole bunch of these sliders for our fictional restaurant; this is a good model for Flyweight.

First, let's build a Slider abstract class (the Flyweight participant):

/// <summary>
/// The Flyweight class
/// </summary>
abstract class Slider  
{
    protected string Name;
    protected string Cheese;
    protected string Toppings;
    protected decimal Price;

    public abstract void Display(int orderTotal);
}

The Slider class has properties for Name, Cheese, Toppings, and Price (all of which are part of the intrinsic state of these objects), and an abstract method Display() which will display the details of that slider.

Now we need our ConcreteFlyweight objects. Let's build three: one each for BaconMaster, VeggieSlider, and BBQKing:

/// <summary>
/// A  ConcreteFlyweight class
/// </summary>
class BaconMaster : Slider  
{
    public BaconMaster()
    {
        Name = "Bacon Master";
        Cheese = "American";
        Toppings = "lots of bacon";
        Price = 2.39m;
    }

    public override void Display(int orderTotal)
    {
        Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString());
    }
}

/// <summary>
/// A ConcreteFlyweight class
/// </summary>
class VeggieSlider : Slider  
{
    public VeggieSlider()
    {
        Name = "Veggie Slider";
        Cheese = "Swiss";
        Toppings = "lettuce, onion, tomato, and pickles";
        Price = 1.99m;
    }

    public override void Display(int orderTotal)
    {
        Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString());
    }

}

/// <summary>
/// A ConcreteFlyweight class
/// </summary>
class BBQKing : Slider  
{
    public BBQKing()
    {
        Name = "BBQ King";
        Cheese = "American";
        Toppings = "Onion rings, lettuce, and BBQ sauce";
        Price = 2.49m;
    }

    public override void Display(int orderTotal)
    {
        Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString());
    }
}

Note that the ConcreteFlyweight classes are, of course, very similar to one another: they all have the same properties. This is critical to using Flyweight: all of the related objects must have the same definition (or at least reasonably close to the same definition).

Finally, we need our FlyweightFactory participant, which will create Flyweight objects. The Factory will store a collection of already-created sliders, and any time another slider of the same type needs to be created, the Factory will use the already-created one rather than creating a brand-new one.

/// <summary>
/// The FlyweightFactory class
/// </summary>
class SliderFactory  
{
    private Dictionary<char, Slider> _sliders =
        new Dictionary<char, Slider>();

    public Slider GetSlider(char key)
    {
        Slider slider = null;
        if (_sliders.ContainsKey(key)) //If we've already created one of the requested type of slider, just use that.
        {
            slider = _sliders[key];
        }
        else //Otherwise, create a brand new instance of the slider.
        {
            switch (key)
            {
                case 'B': slider = new BaconMaster(); break;
                case 'V': slider = new VeggieSlider(); break;
                case 'Q': slider = new BBQKing(); break;
            }
            _sliders.Add(key, slider);
        }
        return slider;
    }
}

All of this comes together in our Main() (which is also our Client participant). Let's pretend we are an order system and we need to take orders for these sliders; the patron can order as many kinds of sliders as s/he wants.

static void Main(string[] args)  
{
    // Build a slider order using patron's input
    Console.WriteLine("Please enter your slider order (use characters B, V, Z with no spaces):");
    var order = Console.ReadLine();
    char[] chars = order.ToCharArray();

    SliderFactory factory = new SliderFactory();

    int orderTotal = 0;

    //Get the slider from the factory
    foreach (char c in chars)
    {
        orderTotal++;
        Slider character = factory.GetSlider(c);
        character.Display(orderTotal);
    }

    Console.ReadKey();
}

When we run the app, we enter as many of those characters as we like to order as many sliders as we like.

A screenshot of the demo app, showing 10 sliders ordered.

Looking at the screenshot above, the FlyweightFactory will have only created new sliders for orders 1, 3, and 4, with every other order being a copy of those objects. This is the power of Flyweight: you can theoretically improve performance by only instantiating new objects on first creation.

Will I Ever Use This Pattern?

Probably not. In theory, this pattern could improve performance, but in practice it's limited to scenarios where you find yourself creating a lot of objects from one or more templates. Further, the entire point of this pattern is to improve performance, and (as I've written about before) performance is not an issue until you can prove that it is, so while refactoring to this pattern may be useful in some extreme circumstances, for most people and most projects the overhead and complexity of the Flyweight pattern outweigh the benefits.

In my opinion, if you need to create lots of instances of an object, you'd be better off using something like the Prototype pattern rather than Flyweight.

Summary

The Flyweight pattern strives to improve performance by creating lots of objects from a small set of "template" objects, where those objects are the same or very similar to all their other instances. In practice, though, the usefulness of this pattern is limited, and you might be better off using Prototype. That said, if anyone has a different opinion on the benefits of Flyweight, I'd love to hear about it, so share 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.