Skip to content
UoL CS Notes

C# Design Patterns (MVC, Factory & Decorator)

COMP282 Lectures

Model-View-Controller

This is a design pattern that splits a user interface into three parts:

  • Model - The internal state and data of the application.
  • View - The GUI elements and how they appear to the user.
  • Controller - Create events that modify the internal state of the application.

MVC Advantages

  • Different parts can be done by different people.
  • High cohesion.
  • Low coupling
  • Easier to maintain.
  • Greater code reuse.

MVC Disadvantages

  • Mode code and higher levels of abstraction.
  • Easier to forget to do a part because the parts are at different places.

Factories

Consider that you have a set of classes and you want to create one depending on an input.

  • We have a set of animal classes and want to create an animal.

We can use the following as a solution:

  1. Give the classes a common interface.
  2. Create a new class named <ClassName>Factory.
  3. This class has a single method, get<ClassName>(), that takes a class and produces a new instance of that class.

Decorators

This pattern can solve the following problems:

  • You want to add a responsibility to an object at run time.
  • You want to do sub-classes but with multiple choice.

We can use the following as a solution:

  1. Create an interface for the class <ClassName> and call it I<Classname>.
  2. Create an <ClassName>Decorator class, implementing I<ClassName> and having an I<ClassName> field.
  3. The constructor takes an I<ClassName> element and puts it into the field.
  4. All methods are just called on that field.
  5. We can then create subclasses of <ClassName>Decorator that will overwrite methods and then do some operations before calling methods on the field.

We can implement this in the following example:

  1. Consider that we are making a text editor that has a Text object. We can implement an IText interface that allows us to define a draw method.
  2. We can make a class TextDecorator that implements IText with an IText field.
  3. TextDecorator has an IText field and takes IText in the constructor.
  4. We can then create subclasses of TextDecorator and use them like so:

     TextFirst(new TextUpper(text));
    

Rule of Three

This rule states that we should wait until we have three of something before we generalise using a design pattern.

  • This saves us putting in extra effort in generalising when we have no need, or too many classes.