The factory method pattern is a creational pattern. You can use it when you don't know witch object you must use at runtime.
Advantage of this pattern; you can delay assigning action code till more information is available. It's also easy to add other classes (in the code example below; color classes).
What happens in the figure above?
The first thing that happens, is that a parameter is passed into the GetInstance method in the Factory class. Depending on the parameter passed in, a object is returned. In this instance, a object from class Blue is returned. The factory method pattern is as simple as that. If I wanted to work with the Green object, I would have passed Green as a parameter.
This patterns can be used in all parts of your code. You can use it to choose, for instance, databases or different graphical user interface frameworks at runtime.
Let's look at some code:
1: using System;
2:
3: namespace FactoryPattern
4: {
5: // Color objects to choose
6: enum MyColors
7: {
8: Green, Blue
9: }
10:
11: // The contract the objects have to implemet
12: interface IColor
13: {
14: void ShowFavoriteColor();
15: }
16:
17: class Factory
18: {
19: // A instance of a object is returned based on the input parameter.
20: public IColor GetInstance(MyColors type)
21: {
22: IColor color = null;
23:
24: // Whice object to return is decided.
25: switch (type)
26: {
27: case MyColors.Green:
28: color = new Green();
29: break;
30: case MyColors.Blue:
31: color = new Blue();
32: break;
33: }
34: return color;
35: }
36: }
37:
38: class Green : IColor
39: {
40: public void ShowFavoriteColor()
41: {
42: Console.WriteLine("My favorite color is green");
43: }
44: }
45:
46: class Blue : IColor
47: {
48: public void ShowFavoriteColor()
49: {
50: Console.WriteLine("My favorite color is blue");
51: }
52: }
53:
54: class ColorChooser
55: {
56: public static void Main()
57: {
58: Factory factory = new Factory();
59:
60: // Decides which instance to start
61: IColor baseClass = factory.GetInstance(MyColors.Blue);
62:
63: // Executes method in chosen instance
64: baseClass.ShowFavoriteColor();
65:
66: Console.ReadKey();
67: }
68: }
69: }
Tags: