Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
4.21/5 (16 votes)
27 Feb 20062 min read 67.3K   1.1K   80   6
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

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

Strategy Example

C#
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.

C#
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

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

View Example

C#
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)

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

Form Creation (using Decorator)

C#
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

C#
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

C#
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


Written By
Web Developer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalgood article Pin
Donsw10-Feb-09 16:34
Donsw10-Feb-09 16:34 
Generalmisleading MVC origins Pin
Martijn van Kleef10-Sep-08 23:28
Martijn van Kleef10-Sep-08 23:28 
QuestionWrong or ugly? Pin
PetziWul19-Mar-06 20:29
PetziWul19-Mar-06 20:29 
AnswerRe: Wrong or ugly? Pin
[Gone]19-Mar-06 20:40
[Gone]19-Mar-06 20:40 
GeneralRe: Wrong or ugly? Pin
PetziWul19-Mar-06 20:49
PetziWul19-Mar-06 20:49 
Answerjust HTML mistake Pin
nashcontrol20-Mar-06 11:37
nashcontrol20-Mar-06 11:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.