Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix patterns of factory #20

Merged
merged 4 commits into from
Feb 28, 2017
Merged

fix patterns of factory #20

merged 4 commits into from
Feb 28, 2017

Conversation

jealone
Copy link
Contributor

@jealone jealone commented Feb 27, 2017

原型模式

修复了一些拼写错误

工厂方法模式

原例子中只是用了工厂方法模式退化为的简单工厂模式,完整的工厂模式应该是可以扩展为多个对象的工厂模式

  • 工厂方法模式可以退化为简单工厂模式(非23中GOF)

抽象工厂模式

原例子中的抽象工厂模式是迭代工厂方法模式,但是抽象工厂模式不是通过工厂返回一个工厂

工厂方法模式和抽象工厂模式的核心区别

  • 工厂方法模式利用继承,抽象工厂模式利用组合
  • 工厂方法模式产生一个对象,抽象工厂模式产生一簇对象(不是一类)
  • 工厂方法模式利用子类创造对象,抽象工厂模式利用接口的实现创造对象

抽象工厂模式在建模过程

  • products对象类型一般是方便穷举的(假设两类,ProductA, ProductB)
  • 通过products的类型数量来决定抽象工厂(IFactory)创造方法的个数(createProductA(), createProductB())
  • 列举需要创建的具体对象(KindAProductA, KindAProductB, KindBProductA, KindBProductB)
  • 实现抽象工厂接口(IFactory)FactoryKindA(创建KindAProductA,KindAProductB)
  • 实现抽象工厂接口(IFactory)FactoryKindB(创建KindBProductA,KindBProductB)

代码中的实现

  • 本来按照原来的例子动物,植物,农场,动物园
  • 如果按照正常逻辑,产品是动物,植物两类
  • 通过products的类型数量来决定抽象工厂(IFactory)创造方法的个数(createAnimal(), createPlant())
  • 列举需要创建的具体对象(动物园熊猫, 农场猪, 农场大米, 动物园牡丹)
  • 实现抽象工厂接口(IFactory)动物园工厂(创建动物园熊猫(createAnimal()),动物园牡丹(createPlant))
  • 实现抽象工厂接口(IFactory)农场工厂(创建农场猪(createAnimal()),农场大米(createPlant))
  • 抽象到这个地方,我们其实会发现我们通过createAnimal通用方法,只能创造一个具体对象,显然不合理,在我需要扩展的时候我得去改createAnimal()这个方法的实现,不满足单一职责原则
  • 其实本例并不适合用抽象工厂模式,因为Animal和Plant本身太宽泛,其实直接用工厂方法模式,创造两个工厂(Animal工厂,Plant工厂)更为合适
  • 如果用抽象工厂模式,反过来看,我们把动物园和农场当做products(Farm,Zoo)
  • 动物和植物作为两个抽象工厂(createFarm(),createZoo())
  • 动物工厂用来创造农场和动物园中以动物为主的部门(PandoZoo,PigFarm(非清真))
  • 植物工厂来创造农场和动物园中以植物为主的部门(PeonyZoo,RiceFarm)
  • 在这种情况下,我可以随意扩展农场部门和动物园部门

@jealone jealone mentioned this pull request Feb 27, 2017
@TIGERB
Copy link
Owner

TIGERB commented Feb 27, 2017

我先仔细看看~ 学习了~

@TIGERB TIGERB merged commit 54a96be into TIGERB:master Feb 28, 2017
@TIGERB
Copy link
Owner

TIGERB commented Feb 28, 2017

done

@jealone jealone deleted the feature_patterns branch March 1, 2017 08:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants