Factory methods are characterized by "methods". sub-classes implement abstract methods of parent classes, and the responsibility for creating products is transferred to sub-classes.
First, use the UML diagram:
Take Dota games as an example. Our factory is a factory that creates models in Dota, while products are different models.
First, we need to clarify the requirements. In Dota, we need to create n medium models, including heroes, monsters, and trees.
Our product categories are as follows:
Public Abstract Class Model
{
Protected Iskill _ skill;
Public Iskill skill
{
Get { Return _ Skill ;}
Set {_ Skill = Value ;}
}
}
Public ClassHeromodel: Model
{
PublicHeromodel ()
{
_ Skill= NewTheurgy ();
}
}
Public ClassBotwildnpcmodel: Model
{
PublicBotwildnpcmodel ()
{
_ Skill= NewNoskill ();
}
}
Carefully dotaer has seen that the product parent class contains an interface iskill, which represents a skill. Skill interfaces and implementations are as follows:
1 Public Interface Iskill
2 {
3 Void Action ();
4 }
5
6 Public Class Theurgy: iskill
7 {
8
9 # Region Iskill Member
10
11 Public Void Action ()
12 {
13 Landpyform. Form. outputresult ( " Cast spells " );
14 }
15
16 # Endregion
17 }
18
19 Public Class Noskill: iskill
20 {
21
22 # Region Iskill Member
23
24 Public Void Action ()
25 {
26 Landpyform. Form. outputresult ( " No skills " );
27 }
28
29 # Endregion
30 }
Now, we are playing in the factory of the main character:
1 Public Abstract Class War3factory
2 {
3 Public Abstract Model createmodel ();
4 }
5
6 Public Class Herofactory: war3factory
7 {
8 Public Override Model createmodel ()
9 {
10 Return New Heromodel ();
11 }
12 }
13
14 Public Class Botwildnpcfactory: war3factory
15 {
16 Public Override Model createmodel ()
17 {
18 Return New Botwildnpcmodel ();
19 }
20 }
The key here isPublic AbstractModel createmodel ();This is the legendary factory "method", which is abstract and not implemented. The specific implementation is integrated into its subclass. There are two sub-classes. One is the hero factory.Herofactor, a strange FactoryBotwildnpcfactory, which implements abstract methods of the parent class.
Let's take a look at the client call.Code:
1 Dotapatternlibrary. factorymethod. war3factory war3factory = New Dotapatternlibrary. factorymethod. herofactory ();
2 Dotapatternlibrary. factorymethod. Model = War3factory. createmodel ();
3 Model. Skill. Action ();
4 War3factory = New Dotapatternlibrary. factorymethod. botwildnpcfactory ();
5 Model = War3factory. createmodel ();
6 Model. Skill. Action ();