10/06: Factory Patterns of DP
- Simple factory pattern
- the instantiation logic will be written in factory method
- ….
- Against Open-Close rule when adding new instance which need to modify above code
- Factory Pattern
- the instantiation logic will be written in client application
- ….
- Not against open-close rule when adding new instance.
- Abstract Factory Pattern.
- Abstract factory pattern is very similar as factory pattern.
- Difference :
- Factory pattern is better used for adding a new object under same family( like add a new peachfactory item to fruitfacotry family)
- Abstract pattern is better used for adding a new brand new family which share similarly with existing family(like database operation component for Oracle , Sqlserver , DB2, SAP, etc).
- Abstract factory return factory object while factory return its subclass object.(so abstract factory is one level higher than factory )
if (!String.IsNullOrEmpty(fruitType))
{
switch (fruitType)
{
case "Apple":
return new Apple();
case "Orange":
return new Orange();
case "Pear":
return new Pear();
case "Banana":
return new Banana();
}
}
//首先要实例化一个苹果工厂
factory = new AppleFactory();
//然后通过工厂来获得苹果类对象
fruit = factory.GetFruit();
//访问苹果类对象
fruit.Display();
//首先要实例化一个梨子工厂
factory = new PearFactory();
//然后通过工厂来获得梨子类对象
fruit = factory.GetFruit();
//访问梨子类对象
fruit.Display();
工厂方法将这些本来应该存在的判断逻辑移到了客户端代码中,
(通过客户的需求来选择生成那一种水果实例,比如我的演示中生成的就是苹果和梨子这两种实例
0 Comments:
Post a Comment
<< Home