您的位置:首页 > 编程语言 > C#

C#设计模式(6)-Abstract Factory Pattern

2010-04-30 11:21 162 查看

一、 抽象工厂(Abstract Factory)模式

抽象工厂模式是所有形态的工厂模式中最为抽象和最具一般性的一种形态。

为了方便引进抽象工厂模式,引进一个新概念:产品族(Product Family)。所谓产品族,是指位于不同产品等级结构,功能相关联的产品组成的家族。如图:

// Abstract Factory pattern -- Structural example
using System;

// "AbstractFactory"
abstract class AbstractFactory

// "ConcreteFactory1"
class ConcreteFactory1 : AbstractFactory

// "ConcreteFactory2"
class ConcreteFactory2 : AbstractFactory

// "AbstractProductA"
abstract class AbstractProductA

// "AbstractProductB"
abstract class AbstractProductB

// "ProductA1"
class ProductA1 : AbstractProductA

// "ProductB1"
class ProductB1 : AbstractProductB

// "ProductA2"
class ProductA2 : AbstractProductA

// "ProductB2"
class ProductB2 : AbstractProductB

// "Client" - the interaction environment of the products
class Environment

class ClientApp
// Abstract Factory pattern -- Real World example
using System;

// "AbstractFactory"
abstract class ContinentFactory

// "ConcreteFactory1"
class AfricaFactory : ContinentFactory

// "ConcreteFactory2"
class AmericaFactory : ContinentFactory

// "AbstractProductA"
abstract class Herbivore

// "AbstractProductB"
abstract class Carnivore

// "ProductA1"
class Wildebeest : Herbivore

// "ProductB1"
class Lion : Carnivore

// "ProductA2"
class Bison : Herbivore

// "ProductB2"
class Wolf : Carnivore

// "Client"
class AnimalWorld

class GameApp
{
public static void Main( string[] args )
{
// Create and run the Africa animal world
ContinentFactory africa = new AfricaFactory();
AnimalWorld world = new AnimalWorld( africa );
world.RunFoodChain();

// Create and run the America animal world
ContinentFactory america = new AmericaFactory();
world = new AnimalWorld( america );
world.RunFoodChain();
}
}

抽象工厂的另外一个例子:



如何设计抽象类工厂留作思考。

七、 "开放-封闭"原则

"开放-封闭"原则要求系统对扩展开放,对修改封闭。通过扩展达到增强其功能的目的。对于涉及到多个产品族与多个产品等级结构的系统,其功能增强包括两方面:

增加产品族:Abstract Factory很好的支持了"开放-封闭"原则。

增加新产品的等级结构:需要修改所有的工厂角色,没有很好支持"开放-封闭"原则。

综合起来,抽象工厂模式以一种倾斜的方式支持增加新的产品,它为新产品族的增加提供方便,而不能为新的产品等级结构的增加提供这样的方便。

参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: