工厂方法,特征就是“方法”上,由子类实现父类的抽象方法,把创建产品的责任转移到子类中。
先上UML图:
还是以Dota游戏为例,我们的工厂是Dota中创建模型的工厂,而产品则是不同的模型。
首先我们要明确需求,Dota中需要创建N中Model,包括英雄、野怪、树木等
那么我们的产品类如下:
public abstract class Model
{
protected ISkill _skill;
public ISkill Skill
{
get { return _skill; }
set { _skill = value; }
}
}
public class HeroModel : Model
{
public HeroModel()
{
_skill = new Theurgy();
}
}
public class BotWildNPCModel : Model
{
public BotWildNPCModel()
{
_skill = new NoSkill();
}
}
{
protected ISkill _skill;
public ISkill Skill
{
get { return _skill; }
set { _skill = value; }
}
}
public class HeroModel : Model
{
public HeroModel()
{
_skill = new Theurgy();
}
}
public class BotWildNPCModel : Model
{
public BotWildNPCModel()
{
_skill = new NoSkill();
}
}
细心的Dotaer已经看到,产品父类包含一个接口ISkill,这个代表技能。技能的接口以及实现如下:
1 public interface ISkill
2 {
3 void Action();
4 }
5
6 public class Theurgy : ISkill
7 {
8
9 #region ISkill 成员
10
11 public void Action()
12 {
13 LandpyForm.Form.OutputResult("施展法术");
14 }
15
16 #endregion
17 }
18
19 public class NoSkill : ISkill
20 {
21
22 #region ISkill 成员
23
24 public void Action()
25 {
26 LandpyForm.Form.OutputResult("没有技能");
27 }
28
29 #endregion
30 }
2 {
3 void Action();
4 }
5
6 public class Theurgy : ISkill
7 {
8
9 #region ISkill 成员
10
11 public void Action()
12 {
13 LandpyForm.Form.OutputResult("施展法术");
14 }
15
16 #endregion
17 }
18
19 public class NoSkill : ISkill
20 {
21
22 #region ISkill 成员
23
24 public void Action()
25 {
26 LandpyForm.Form.OutputResult("没有技能");
27 }
28
29 #endregion
30 }
好了,下面该我们的主角工厂方法上场了:
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 }
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 }
这里的关键在public abstract Model CreateModel();这就是传说中的工厂“方法”,他是抽象的,没有实现,具体实现在集成他的子类中。有两个子类,一个是英雄工厂HeroFactor,一个是野怪工厂BotWildNPCFactory,他们都实现了父类的抽象方法。
再来看下客户端调用代码:
1 DotaPatternLibrary.FactoryMethod.War3Factory war3Factory = new DotaPatternLibrary.FactoryMethod.HeroFactory();
2 DotaPatternLibrary.FactoryMethod.Model model = war3Factory.CreateModel();
3 model.Skill.Action();
4 war3Factory = new DotaPatternLibrary.FactoryMethod.BotWildNPCFactory();
5 model = war3Factory.CreateModel();
6 model.Skill.Action();
2 DotaPatternLibrary.FactoryMethod.Model model = war3Factory.CreateModel();
3 model.Skill.Action();
4 war3Factory = new DotaPatternLibrary.FactoryMethod.BotWildNPCFactory();
5 model = war3Factory.CreateModel();
6 model.Skill.Action();