Applying the Decorator Pattern to Forms

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-03-31T15:22:04Z Indexed on 2010/03/31 18:43 UTC
Read the original article Hit count: 261

Filed under:
|
|

I am trying to apply the Decorator Design Pattern to the following situation:

I have 3 different kind of forms: Green, Yellow, Red.

Now, each of those forms can have different set of attributes. They can have a minimize box disabled, a maximized box disabled and they can be always on top.

I tried to model this the following way:

              Form <---------------------------------------FormDecorator
              /\                                                  /\
     |---------|-----------|               |----------------------|-----------------|
GreenForm  YellowForm   RedForm  MinimizeButtonDisabled MaximizedButtonDisabled AlwaysOnTop

Here is my GreenForm code:

public class GreenForm : Form {
    public GreenForm() {
        this.BackColor = Color.GreenYellow;
    }

    public override sealed Color BackColor {
        get { return base.BackColor; }
        set { base.BackColor = value; }
    }
}

FormDecorator:

public abstract class FormDecorator : Form {
    private Form _decoratorForm;

    protected FormDecorator(Form decoratorForm) {
        this._decoratorForm = decoratorForm;
    }
}

and finally NoMaximizeDecorator:

public class NoMaximizeDecorator : FormDecorator
{
    public NoMaximizeDecorator(Form decoratorForm) : base(decoratorForm) {
        this.MaximizeBox = false;
    }
}

So here is the running code:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(CreateForm());
}

static Form CreateForm() {
    Form form = new GreenForm();
    form = new NoMaximizeDecorator(form);
    form = new NoMinimizeDecorator(form);

    return form;
}

The problem is that I get a form that isn't green and that still allows me to maximize it. It is only taking in consideration the NoMinimizeDecorator form. I do comprehend why this happens but I'm having trouble understanding how to make this work with this Pattern.

I know probably there are better ways of achieving what I want. I made this example as an attempt to apply the Decorator Pattern to something. Maybe this wasn't the best pattern I could have used(if one, at all) to this kind of scenario. Is there any other pattern more suitable than the Decorator to accomplish this? Am I doing something wrong when trying to implement the Decorator Pattern?

Thanks

© Stack Overflow or respective owner

Related posts about decorator

Related posts about c#