Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Implementing Observer, Strategy, and Decorator Design Patterns on a Temperature Model

0.00/5 (No votes)
27 Feb 2006 2  
This article demonstrates the use of the Observer, Strategy, and Decorator patterns in C#.

Preview

Introduction

Design Patterns were created by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, known as the "Gang of Four" or simply "GoF". They are standard solutions to common problems in software design. Instead of focusing on how individual components work, design patterns take a systematic approach, which focuses on the patterns of interaction. Design patterns describe abstract systems of interaction between classes, objects, and communication flow.

Background

This program is a demonstration of the Model-View-Controller (MVC) design pattern, allowing the separation of the user interface, the data model (temperature), and the code which is used to connect the two. The program was translated to C# from Joseph Bergin's Building Graphical User Interfaces with the MVC Pattern.

Observer Pattern

The basic pattern used is the Observer pattern, which is implemented as a combination of a Delegate and an Event. This is the best way for updating an object's state on all observers.

Strategy Pattern

Being required to present both Fahrenheit degrees and Celsius degrees in the same application, thus making a form for each, is just a waste of time. Applying a Strategy design pattern to factor out the small changes is best suited. The Strategy is implemented as an abstract class, and both CelsiusStrategy and FarenheitStrategy implement it:

UMLView

public abstract class ValueStrategy
{
    public abstract double Temperature{get;set;}
    protected TemperatureModel model;
}

Strategy Example

public class CelsiusStrategy : ValueStrategy
{
    public CelsiusStrategy(TemperatureModel m)
    {
        model = m;
    }    
    public override double Temperature
    {
        set
        {
    
            model.C = value;
        }
        get
        {
            return model.C;
        }
    }
}

The Model

The TemperatureModel allows converting Fahrenheit degrees to Celsius degrees, and then updates all the observers by raising an event.

public class TemperatureModel
{
    public delegate void 
           TemperatureChangedHandler(object sender, EventArgs e);
    
    public event TemperatureChangedHandler TemperatureChanged;

    //default value

    private double temperatureF = 32.0;

    //Farenheit

    public double F
    {
        get {return temperatureF;}
        set 
        {
            temperatureF = value;

            //raise event

            OnTemperatureChanged();
        }
    }

    //Celsius

    public double C
    {
        get {return (temperatureF - 32.0) * 5.0 / 9.0;}
        set 
        {
            temperatureF = value*9.0/5.0 + 32.0;
            
            //raise event

            OnTemperatureChanged();
        }
    }
    
    public TemperatureModel(double Temperature) 
    {
        temperatureF = Temperature;
    }

    public TemperatureModel()
    {

    }

    private void OnTemperatureChanged()
    {
        TemperatureChanged(this, new EventArgs());
    }
    
}

The View

Each view must implement the TemperatureDisplay method, for displaying the changes in the temperature model:

UMLView

public interface IView
{
    void TemperatureDisplay(object sender, EventArgs e);
}

View Example

public class TemperatureForm : 
             System.Windows.Forms.Form, IView
{
    
    public System.Windows.Forms.TextBox textBoxTemprerature;
    public TemperatureModel Temperature;
    public ValueStrategy valueStrategy;
    
    public void TemperatureDisplay(object sender, EventArgs e)
    {
        textBoxTemprerature.Text = 
               valueStrategy.Temperature.ToString();
    }
}

Form Creation (using Strategy)

TemperatureForm celsius = new TemperatureForm("Celsius");
celsius.valueStrategy = new CelsiusStrategy(temperature);
celsius.Show();
temperature.TemperatureChanged+= new 
  TemperatureModel.TemperatureChangedHandler(
  celsius.TemperatureDisplay);

Form Creation (using Decorator)

FarenheitScroll farenheitScroll = new FarenheitScroll();
farenheitScroll.valueStrategy = new ValueDecorator(new 
                                CelsiusStrategy(temperature),150,-100);
farenheitScroll.MaxTemp = 150;
farenheitScroll.MinTemp = -100;
farenheitScroll.Show();
temperature.TemperatureChanged+= new 
            TemperatureModel.TemperatureChangedHandler(
            farenheitScroll.TemperatureDisplay);

Decorator Pattern

Decorators are used to provide additional functionality to an object of some kind. The key to a decorator is that a decorator "wraps" the object decorated and looks to a client exactly the same as the object wrapped. This means that the decorator implements the same interface as the object it decorates.

You can think of a decorator as a shell around the object decorated. Any message that a client sends to the object is caught by the decorator instead. The decorator may apply some action and then pass the message it received on to the decorated object. That object probably returns a value (to the decorator) which may again apply an action to that result, finally sending the (perhaps modified) result to the original client. To the client, the decorator is invisible. It just sent a message and got a result. However, the decorator has two chances to enhance the result returned.

In this program, the Decorator allows setting minimum and maximum temperatures:

UMLView

ValueDecorator

public class ValueDecorator : ValueStrategy
{
    ValueStrategy strategy;
    private int maxTemp = 300;
    private int minTemp = -200;

    //temp Temperature for limiting

    private double tempTemp;

    public ValueDecorator(ValueStrategy valueStrategy)
    {
        strategy = valueStrategy;
        tempTemp = strategy.Temperature;
    }

    public ValueDecorator(ValueStrategy valueStrategy, 
                          int MaxTemp, int MinTemp)
    {
        strategy = valueStrategy;
        tempTemp = strategy.Temperature;
        maxTemp = MaxTemp;
        minTemp = MinTemp;
    }

    public override double Temperature
    {
        set
        {
            if (value < maxTemp && value > minTemp)
            strategy.Temperature = value;
        }
        get
        {
            if (strategy.Temperature < maxTemp && 
                strategy.Temperature > minTemp)
            {
                tempTemp = strategy.Temperature;
                return strategy.Temperature;
            }
            else
            {
                strategy.Temperature = tempTemp;
                return tempTemp;
            }
        }
    }
}

A View using the Decorator

FarenheitScroll farenheitScroll = new FarenheitScroll();
farenheitScroll.valueStrategy = new ValueDecorator(new 
                CelsiusStrategy(temperature),150,-100);
farenheitScroll.MaxTemp = 150;
farenheitScroll.MinTemp = -100;
farenheitScroll.Show();
temperature.TemperatureChanged+= new 
  TemperatureModel.TemperatureChangedHandler(
  farenheitScroll.TemperatureDisplay);

Further Development

  • Applying Command pattern for Undo/Redo capabilities.

Acknowledgements

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here