Drawing Blanks

Premature Optimization is a Prerequisite for Success

The Flyweight Design Pattern

leave a comment »

I think that the Flyweight Pattern is underrated. It is not all about saving memory. In many cases, Flyweights also add convenient syntax and clear semantics to the code. They are almost like “enums on steroids”. Here is a coding idiom that I frequently use:

class Flavor
{
    private Flavor(string displayName, Color colorCode)
    {
        this.displayName = displayName;
        this.colorCode = colorCode;
    }

    private string displayName;
    public string DisplayName { get { return displayName; } }
    private Color colorCode;
    public Color ColorCode { get { return colorCode; } }
    
    public static readonly Flavor Vanilla = 
        new Flavor("Vanilla", Color.FromRgb(0xF4, 0xE7, 0xC6));
    public static readonly Flavor Chocolate = 
        new Flavor("Chocolate", Color.FromRgb(0x8B, 0x45, 0x13));
    public static readonly Flavor Pineapple = 
        new Flavor("Pineapple", Color.FromRgb(0xEE, 0xEE, 0x00));

    public static IEnumerable<Flavor> AllFlavors
    {
        get { yield return Vanilla; yield return Chocolate; yield return Pineapple; }
    }

    public static Flavor Parse(string displayName)
    {
        return (from f in AllFlavors 
                where string.Compare(f.displayName, displayName) == 0 
                select f).First();
    }
}

 

Now we can do tons of convenient things like:

icecream.Flavor = Flavor.Chocolate;
if (icecream.Flavor == Flavor.Vanilla) {…}
comboBox.DataContext = Flavor.AllFlavors;
productPanel.Background = new SolidColorBrush(icecream.Flavor.ColorCode);

Advertisements

Written by bbzippo

10/26/2010 at 5:18 am

Posted in programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: