C# Design Patterns (MVC, Factory & Decorator)
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:
- Give the classes a common interface.
- Create a new class named
<ClassName>Factory. - 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:
- Create an interface for the class
<ClassName>and call itI<Classname>. - Create an
<ClassName>Decoratorclass, implementingI<ClassName>and having anI<ClassName>field. - The constructor takes an
I<ClassName>element and puts it into the field. - All methods are just called on that field.
- We can then create subclasses of
<ClassName>Decoratorthat will overwrite methods and then do some operations before calling methods on the field.
We can implement this in the following example:
- Consider that we are making a text editor that has a
Textobject. We can implement anITextinterface that allows us to define adrawmethod. - We can make a class
TextDecoratorthat implementsITextwith anITextfield. TextDecoratorhas anITextfield and takesITextin the constructor.-
We can then create subclasses of
TextDecoratorand 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.