您的位置:首页 > 其它

学习设计模式第五 - 抽象工厂模式

2014-01-07 16:55 375 查看

本文摘取自TerryLee(李会军)老师的设计模式系列文章,版权归TerryLee,仅供个人学习参考。转载请标明原作者TerryLee。部分示例代码来自DoFactory



概述

在软件系统中,经常面临着"一系列相互依赖的对象"的创建工作;同时由于需求的变化,往往存在着更多系列对象的创建工作。如何应对这种变化?如何绕过常规的对象的创建方法(new),提供一种"封装机制"来避免客户程序和这种"多系列具体对象创建工作"的紧耦合?这就是我们要说的抽象工厂模式。

意图

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

UML



图1. 抽象工厂模式UML图

参与者

这个模式涉及的类或对象:

AbstractFactory

定义一个包含创建抽象产品的操作的接口

ConcreteFactory

实现创建具体产品对象的操作

AbstractProduct

定义一个产品系列的接口

Product

定义一个实现了AbstractProduct接口的产品,其由对应的具体工厂进行创建。

Client

调用AbstractFactory及AbstractProduct抽象类/接口完成工作。

适用性

抽象工厂模式应用的一个很经典的例子是如Qt这种跨平台的GUI框架,其可以在不同的平台,如Windows、MAC或Linux,上创建相同的控件,如Button、ListBox等。这个例子最核心的一点是创建出来的控件功能一致,且不依赖于其平台(平台无关性)。

什么情况下应该使用Factory而非构造函数来创建对象呢?几个常见的场景:对象的构建过程涉及到对象的缓存,涉及到共享或重用的对象或应用程序需要维护对象或类型的数量。另一个好处是我们可以通过定义不同的工厂方法的名称来方便客户知道调用哪个方法得到想要的对象。而构造方法只能通过不同的重载来构建不同的对象,但很难通过名称知道它们具体构造哪个对象。

在抽象工厂模式中,我们使用不同的具体工厂决定生产出来的拥有共同父类的产品具体是什么类型。一个很类似的设计是ADO.NET的设计,系统根据Provider的不同产生各种具体的DbConnection,DbCommand或DbDataAdapter。

在以下情况下应当考虑使用抽象工厂模式:

一个系统不应当依赖于产品类实例如何被创建、组合和表达的细节,这对于所有形态的工厂模式都是重要的。

这个系统有多于一个的产品族,而系统只消费其中某一产品族。

同属于同一个产品族的产品是在一起使用的,这一约束必须在系统的设计中体现出来。

系统提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于实现。

DoFactory GoF代码

// Abstract Factory Pattern
// Structural example
using System;

namespace DoFactory.GangOfFour.Abstract.Structural
{
class MainApp
{
public static void Main()
{
// Abstract factory #1
AbstractFactory factory1 = new ConcreteFactory1();
Client client1 = new Client(factory1);
client1.Run();

// Abstract factory #2
AbstractFactory factory2 = new ConcreteFactory2();
Client client2 = new Client(factory2);
client2.Run();

// Wait for user input
Console.ReadKey();
}
}

// "AbstractFactory"
abstract class AbstractFactory
{
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}

// "ConcreteFactory1"
class ConcreteFactory1 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}

// "ConcreteFactory2"
class ConcreteFactory2 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}

// "AbstractProductA"
abstract class AbstractProductA
{
}

// "AbstractProductB"
abstract class AbstractProductB
{
public abstract void Interact(AbstractProductA a);
}

// "ProductA1"
class ProductA1 : AbstractProductA
{
}

// "ProductB1"
class ProductB1 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " interacts with " + a.GetType().Name);
}
}

// "ProductA2"
class ProductA2 : AbstractProductA
{
}

// "ProductB2"
class ProductB2 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + " interacts with " + a.GetType().Name);
}
}

// "Client" - Interaction environment for the products.
class Client
{
private AbstractProductA _abstractProductA;
private AbstractProductB _abstractProductB;

// Constructor
public Client(AbstractFactory factory)
{
_abstractProductB = factory.CreateProductB();
_abstractProductA = factory.CreateProductA();
}

public void Run()
{
_abstractProductB.Interact(_abstractProductA);
}
}
}

下面例子中涉及到的类与抽象工厂模式中标准的类对应关系如下:

AbstractFactory - ContinentFactory

ConcreteFactory - AfricaFactory, AmericaFactory

AbstractProduct - Herbivore, Carnivore

Product - Wildebeest, Lion, Bison, Wolf

Client – AnimalWorld

本例值得一提的一点是,虽然不同点动物工厂生产的动物种类不同,但动物之间的交互动作是相同的。

// Abstract Factory Pattern
// Real World example
using System;

namespace DoFactory.GangOfFour.Abstract.RealWorld
{
class MainApp
{

public static void Main()
{
// Create and run the African animal world
ContinentFactory africa = new AfricaFactory();
AnimalWorld world = new AnimalWorld(africa);
world.RunFoodChain();

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

// Wait for user input
Console.ReadKey();
}
}

// "AbstractFactory"
abstract class ContinentFactory
{
public abstract Herbivore CreateHerbivore();
public abstract Carnivore CreateCarnivore();
}

// "ConcreteFactory1"
class AfricaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Wildebeest();
}
public override Carnivore CreateCarnivore()
{
return new Lion();
}
}

// "ConcreteFactory2"
class AmericaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Bison();
}
public override Carnivore CreateCarnivore()
{
return new Wolf();
}
}

// "AbstractProductA"
abstract class Herbivore
{
}

// "AbstractProductB"
abstract class Carnivore
{
public abstract void Eat(Herbivore h);
}

// "ProductA1"
class Wildebeest : Herbivore
{
}

// "ProductB1"
class Lion : Carnivore
{
public override void Eat(Herbivore h)
{
// Eat Wildebeest
Console.WriteLine(this.GetType().Name + " eats " + h.GetType().Name);
}
}

// "ProductA2"
class Bison : Herbivore
{
}

// "ProductB2"
class Wolf : Carnivore
{
public override void Eat(Herbivore h)
{
// Eat Bison
Console.WriteLine(this.GetType().Name + " eats " + h.GetType().Name);
}
}

// "Client"
class AnimalWorld
{
private Herbivore _herbivore;
private Carnivore _carnivore;

// Constructor
public AnimalWorld(ContinentFactory factory)
{
_carnivore = factory.CreateCarnivore();
_herbivore = factory.CreateHerbivore();
}

public void RunFoodChain()
{
_carnivore.Eat(_herbivore);
}
}
}

在下面.NET版本的例子中,使用接口取代了抽象类(因为这些抽象基类中没有任何实际操作),在客户类实现过程中使用了泛型,通过泛型参数获得工厂的类型。

// Abstract Factory Design Pattern
//.NET optimized example
using System;

namespace DoFactory.GangOfFour.Abstract.NETOptimized
{
class MainApp
{
public static void Main()
{
// Create and run the African animal world
var africa = new AnimalWorld<Africa>();
africa.RunFoodChain();

// Create and run the American animal world
var america = new AnimalWorld<America>();
america.RunFoodChain();

// Wait for user input
Console.ReadKey();
}
}

// "AbstractFactory“
interface IContinentFactory
{
IHerbivore CreateHerbivore();
ICarnivore CreateCarnivore();
}

// "ConcreteFactory1"
class Africa : IContinentFactory
{
public IHerbivore CreateHerbivore()
{
return new Wildebeest();
}

public ICarnivore CreateCarnivore()
{
return new Lion();
}
}

// "ConcreteFactory2"
class America : IContinentFactory
{
public IHerbivore CreateHerbivore()
{
return new Bison();
}

public ICarnivore CreateCarnivore()
{
return new Wolf();
}
}

// "AbstractProductA"
interface IHerbivore
{
}

// "AbstractProductB"
interface ICarnivore
{
void Eat(IHerbivore h);
}

// "ProductA1"
class Wildebeest : IHerbivore
{
}

// "ProductB1"
class Lion : ICarnivore
{
public void Eat(IHerbivore h)
{
// Eat Wildebeest
Console.WriteLine(this.GetType().Name +
" eats " + h.GetType().Name);
}
}

// "ProductA2"
class Bison : IHerbivore
{
}

// "ProductB2"
class Wolf : ICarnivore
{
public void Eat(IHerbivore h)
{
// Eat Bison
Console.WriteLine(this.GetType().Name +
" eats " + h.GetType().Name);
}
}

// "Client" interface
interface IAnimalWorld
{
void RunFoodChain();
}

// "Client"
class AnimalWorld<T> : IAnimalWorld where T : IContinentFactory, new()
{
private IHerbivore _herbivore;
private ICarnivore _carnivore;
private T _factory;

/// <summary>
/// Contructor of Animalworld
/// </summary>
public AnimalWorld()
{
// Create new continent factory
_factory = new T();

// Factory creates carnivores and herbivores
_carnivore = _factory.CreateCarnivore();
_herbivore = _factory.CreateHerbivore();
}

/// <summary>
/// Runs the foodchain, that is, carnivores are eating herbivores.
/// </summary>
public void RunFoodChain()
{
_carnivore.Eat(_herbivore);
}
}
}


抽象工厂之新解

虚拟案例

中国企业需要一项简单的财务计算:每月月底,财务人员要计算员工的工资。员工的工资= (基本工资 + 奖金 - 个人所得税)。这是一个放之四海皆准的运算法则。

为了简化系统,我们假设员工基本工资总是4000美金。中国企业奖金和个人所得税的计算规则是:

奖金 = 基本工资(4000) * 10%

个人所得税 = (基本工资 + 奖金) * 40%

我们现在要为此构建一个软件系统(代号叫Softo),满足中国企业的需求。

案例分析

奖金(Bonus)、个人所得税(Tax)的计算是Softo系统的业务规则(Service)。工资的计算(Calculator)则调用业务规则(Service)来计算员工的实际工资。工资的计算作为业务规则的前端(或者客户端Client)将提供给最终使用该系统的用户(财务人员)使用。

针对中国企业为系统建模

根据上面的分析,为Softo系统建模如下:



图2. 示例-中国企业薪资计算程序逻辑架构

业务规则Service类的代码如下:

namespace ChineseSalary
{
// 公用的常量
public class Constant
{
public static double BASE_SALARY = 4000;
}

// 计算中国个人奖金
public class ChineseBonus
{
public double Calculate()
{
return Constant.BASE_SALARY * 0.1;
}
}

// 计算中国个人所得税
public class ChineseTax
{
public double Calculate()
{
return (Constant.BASE_SALARY + (Constant.BASE_SALARY * 0.1)) * 0.4;
}
}
}

客户端程序:

namespace ChineseSalary
{
// 客户端程序调用
public class Calculator
{
public static void Main(string[] args)
{
ChineseBonus bonus = new ChineseBonus();
double bonusValue = bonus.Calculate();

ChineseTax tax = new ChineseTax();
double taxValue = tax.Calculate();

double salary = 4000 + bonusValue - taxValue;

Console.WriteLine("Chinese Salary is:" + salary);
Console.ReadLine();
}
}
}

运行程序,输入的结果如下:


Chinese Salary is:2640


针对美国企业为系统建模

为了拓展国际市场,我们要把该系统移植给美国公司使用。美国企业的工资计算同样是: 员工的工资 = 基本工资 + 奖金 - 个人所得税。但是他们的奖金和个人所得税的计算规则不同于中国企业:

美国企业奖金和个人所得税的计算规则是:

奖金 = 基本工资 * 15 %

个人所得税 = (基本工资 * 5% + 奖金 * 25%)

根据前面为中国企业建模经验,我们仅仅将ChineseTax、ChineseBonus修改为AmericanTax、AmericanBonus。修改后的模型如下:



图3. 示例-美国企业薪资计算程序逻辑架构

则业务规则Service类的代码如下:

namespace AmericanSalary
{
// 公用的常量
public class Constant
{
public static double BASE_SALARY = 4000;
}

// 计算美国个人奖金
public class AmericanBonus
{
public double Calculate()
{
return Constant.BASE_SALARY * 0.15;
}
}

// 计算美国个人所得税
public class AmericanTax
{
public double Calculate()
{
return Constant.BASE_SALARY * 0.05 + Constant.BASE_SALARY * 0.15 * 0.25;
}
}
}

客户端的调用代码:

namespace AmericanSalary
{
// 客户端程序调用
public class Calculator
{
public static void Main(string[] args)
{
AmericanBonus bonus = new AmericanBonus();
double bonusValue = bonus.Calculate();

AmericanTax tax = new AmericanTax();
double taxValue = tax.Calculate();

double salary = 4000 + bonusValue - taxValue;

Console.WriteLine("American Salary is:" + salary);
Console.ReadLine();
}
}
}

运行程序,输入的结果如下:


American Salary is:4250


整合成通用系统

让我们回顾一下该系统的发展历程:

最初,我们只考虑将Softo系统运行于中国企业。但随着MaxDO公司业务向海外拓展, MaxDO需要将该系统移植给美国使用。

移植时,MaxDO不得不抛弃中国企业的业务规则类ChineseTax和ChineseBonus,然后为美国企业新建两个业务规则类: AmericanTax,AmericanBonus。最后修改了业务规则调用Calculator类。

结果我们发现:每当Softo系统移植的时候,就抛弃原来的类。现在,如果中国联想集团要购买该系统,我们不得不再次抛弃AmericanTax,AmericanBonus,修改回原来的业务规则。

一个可以立即想到的做法就是在系统中保留所有业务规则模型,即保留中国和美国企业工资运算规则。



图4. 企业薪资计算程序逻辑架构

通过保留中国企业和美国企业的业务规则模型,如果该系统在美国企业和中国企业之间切换时,我们仅仅需要修改Caculator类即可。

让移植工作更简单

前面系统的整合问题在于:当系统在客户在美国和中国企业间切换时仍然需要修改Caculator代码。

一个维护性良好的系统应该遵循"开闭原则"。即:封闭对原来代码的修改,开放对原来代码的扩展(如类的继承,接口的实现)

我们发现不论是中国企业还是美国企业,他们的业务运规则都采用同样的计算接口。于是很自然地想到建立两个业务接口类Tax,Bonus,然后让AmericanTax、AmericanBonus和ChineseTax、ChineseBonus分别实现这两个接口,据此修正后的模型如下:



图5. 企业薪资计算程序改进型逻辑架构

此时客户端代码如下:

namespace InterfaceSalary
{
// 客户端程序调用
public class Calculator
{
public static void Main(string[] args)
{
Bonus bonus = new ChineseBonus();
double bonusValue = bonus.Calculate();

Tax tax = new ChineseTax();
double taxValue = tax.Calculate();

double salary = 4000 + bonusValue - taxValue;

Console.WriteLine("Chinaese Salary is:" + salary);
Console.ReadLine();
}
}
}

为业务规则增加工厂方法

然而,上面增加的接口几乎没有解决任何问题,因为当系统的客户在美国和中国企业间切换时Caculator代码仍然需要修改。

只不过修改少了两处,但是仍然需要修改ChineseBonus,ChineseTax部分。致命的问题是:我们需要将这个移植工作转包给一个叫Hippo的软件公司。由于版权问题,我们并未提供Softo系统的源码给Hippo公司,因此Hippo公司根本无法修改Calculator,导致实际上移植工作无法进行。

为此,我们考虑增加一个工具类(命名为Factory),代码如下:

namespace FactorySalary
{
// Factory类
public class Factory
{
public Tax CreateTax()
{
return new ChineseTax();
}

public Bonus CreateBonus()
{
return new ChineseBonus();
}
}
}

修改后的客户端代码:

namespace FactorySalary
{
// 客户端程序调用
public class Calculator
{
public static void Main(string[] args)
{
Bonus bonus = new Factory().CreateBonus();
double bonusValue = bonus.Calculate();

Tax tax = new Factory().CreateTax();
double taxValue = tax.Calculate();

double salary = 4000 + bonusValue - taxValue;

Console.WriteLine("Chinaese Salary is:" + salary);
Console.ReadLine();
}
}
}

不错,我们解决了一个大问题,设想一下:当该系统从中国企业移植到美国企业时,我们现在需要做什么?

答案是: 对于Caculator类我们什么也不用做。我们需要做的是修改Factory类,修改结果如下:

namespace FactorySalary
{
// Factory类
public class Factory
{
public Tax CreateTax()
{
return new AmericanTax();
}

public Bonus CreateBonus()
{
return new AmericanBonus();
}
}
}

为系统增加抽象工厂方法

很显然,前面的解决方案带来了一个副作用:就是系统不但增加了新的类Factory,而且当系统移植时,移植工作仅仅是转移到Factory类上,工作量并没有任何缩减,而且还是要修改系统的源码。从Factory类在系统移植时修改的内容我们可以看出: 实际上它是专属于美国企业或者中国企业的。名称上应该叫AmericanFactory,ChineseFactory更合适.

解决方案是增加一个抽象工厂类AbstractFactory,增加一个静态方法,该方法根据一个配置文件的一个项(比如factoryName)动态地判断应该实例化哪个工厂类,这样,我们就把移植工作转移到了对配置文件的修改。修改后的模型和代码:



图6. 使用抽象工厂改进的企业薪资计算程序逻辑架构

抽象工厂类的代码如下:

namespace AbstractFactory
{
// AbstractFactory类
public abstract class AbstractFactory
{
public static AbstractFactory GetInstance()
{
string factoryName = Constant.STR_FACTORYNAME.ToString();

AbstractFactory instance;

if (factoryName == "ChineseFactory")
instance = new ChineseFactory();
else if (factoryName == "AmericanFactory")
instance = new AmericanFactory();
else
instance = null;

return instance;
}

public abstract Tax CreateTax();

public abstract Bonus CreateBonus();
}
}

配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="factoryName" value="AmericanFactory"></add>
</appSettings>
</configuration>

采用上面的解决方案,当系统在美国企业和中国企业之间切换时,我们需要做什么移植工作?答案是: 我们仅仅需要修改配置文件,将factoryName的值改为American。修改配置文件的工作很简单,只要写一篇幅配置文档说明书提供给移植该系统的团队(比如Hippo公司) 就可以方便地切换使该系统运行在美国或中国企业。

最后的修正(不是最终方案)

前面的解决方案几乎很完美,但是还有一点瑕疵,瑕疵虽小,但可能是致命的。

考虑一下,现在日本NEC公司决定购买该系统,NEC公司的工资的运算规则遵守的是日本的法律。如果采用上面的系统构架,这个移植我们要做哪些工作呢?

增加新的业务规则类JapaneseTax,JapaneseBonus分别实现Tax和Bonus接口。

修改AbstractFactory的getInstance方法,增加else if(factoryName.equals("Japanese")){....

注意: 系统中增加业务规则类不是模式所能解决的,无论采用什么设计模式,JapaneseTax,JapaneseBonus总是少不了的。(即增加了新系列产品)

我们真正不能接受的是:我们仍然修要修改系统中原来的类(AbstractFactory)。前面提到过该系统的移植工作,我们可能转包给一个叫Hippo的软件公司。为了维护版权,未将该系统的源码提供给Hippo公司,那么Hippo公司根本无法修改AbstractFactory,所以系统移植其实无从谈起,或者说系统移植总要开发人员亲自参与。

解决方案是将抽象工厂类中的条件判断语句,用.NET中发射机制代替,修改如下:

using System;
using System.Reflection;

namespace AbstractFactory
{
// AbstractFactory类
public abstract class AbstractFactory
{
public static AbstractFactory GetInstance()
{
string factoryName = Constant.STR_FACTORYNAME.ToString();

AbstractFactory instance;

if (factoryName != "")
instance = (AbstractFactory)Assembly.Load(factoryName).CreateInstance(factoryName);
else
instance = null;

return instance;
}

public abstract Tax CreateTax();

public abstract Bonus CreateBonus();
}
}

这样,在我们编写的代码中就不会出现Chinese,American,Japanese等这样的字眼了。

例子小结:

最后那幅图是最终版的系统模型图。我们发现作为客户端角色的Calculator仅仅依赖抽象类,它不必去理解中国和美国企业具体的业务规则如何实现,Calculator面对的仅仅是业务规则接口Tax和Bonus。

Softo系统的实际开发的分工可能是一个团队专门做业务规则,另一个团队专门做前端的业务规则组装。抽象工厂模式有助于这样的团队的分工: 两个团队通讯的约定是业务接口,由抽象工厂作为纽带粘合业务规则和前段调用,大大降低了模块间的耦合性,提高了团队开发效率。

完完全全地理解抽象工厂模式的意义非常重大,可以说对它的理解是你对OOP理解上升到一个新的里程碑的重要标志。学会了用抽象工厂模式编写框架类,你将理解OOP的精华:面向接口编程。

应对"新对象"

抽象工厂模式主要在于应对"新系列"的需求变化。其缺点在于难于应付"新对象"的需求变动。如果在开发中出现了新对象,该如何去解决呢?这个问题并没有一个好的答案,下面我们看一下李建忠老师的回答:

"GOF《设计模式》中提出过一种解决方法,即给创建对象的操作增加参数,但这种做法并不能令人满意。事实上,对于新系列加新对象,就我所知,目前还没有完美的做法,只有一些演化的思路,这种变化实在是太剧烈了,因为系统对于新的对象是完全陌生的。"

来自《深入浅出设计模式》的例子

这个例子仍然是与比萨店有关,而重点却转移到不同的原料工厂作为不同的抽象工厂生产一系列制作比萨所需的原料提供给与其相关的比萨店。在这里使用抽象工厂模式可以实现当客户选择了一个原料工厂则其就确定了一家使用此原料的比萨店。

这个例子的UML图如下:



图7 比萨店例子的UML图

using System;
using System.Text;

namespace DoFactory.HeadFirst.Factory.Abstract.Pizza
{
// PizzaTestDrive test application
class PizzaTestDrive
{
static void Main(string[] args)
{
PizzaStore nyStore = new NewYorkPizzaStore();
PizzaStore chStore = new ChicagoPizzaStore();

Pizza pizza = nyStore.OrderPizza("cheese");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");

pizza = chStore.OrderPizza("cheese");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");

pizza = nyStore.OrderPizza("clam");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");

pizza = chStore.OrderPizza("clam");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");

pizza = nyStore.OrderPizza("pepperoni");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");

pizza = chStore.OrderPizza("pepperoni");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");

pizza = nyStore.OrderPizza("veggie");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");

pizza = chStore.OrderPizza("veggie");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");

// Wait for user
Console.ReadKey();
}
}

#region Ingredient Abstract Factory

public interface IPizzaIngredientFactory
{
IDough CreateDough();
ISauce CreateSauce();
ICheese CreateCheese();
IVeggies[] CreateVeggies();
IPepperoni CreatePepperoni();
IClams CreateClam();
}

public class NewYorkPizzaIngredientFactory : IPizzaIngredientFactory
{
public IDough CreateDough()
{
return new ThinCrustDough();
}

public ISauce CreateSauce()
{
return new MarinaraSauce();
}

public ICheese CreateCheese()
{
return new ReggianoCheese();
}

public IVeggies[] CreateVeggies()
{
IVeggies[] veggies = { new Garlic(),
new Onion(),
new Mushroom(),
new RedPepper() };
return veggies;
}

public IPepperoni CreatePepperoni()
{
return new SlicedPepperoni();
}

public IClams CreateClam()
{
return new FreshClams();
}
}

public class ChicagoPizzaIngredientFactory : IPizzaIngredientFactory
{

public IDough CreateDough()
{
return new ThickCrustDough();
}

public ISauce CreateSauce()
{
return new PlumTomatoSauce();
}

public ICheese CreateCheese()
{
return new MozzarellaCheese();
}

public IVeggies[] CreateVeggies()
{
IVeggies[] veggies = { new BlackOlives(),
new Spinach(),
new Eggplant() };
return veggies;
}

public IPepperoni CreatePepperoni()
{
return new SlicedPepperoni();
}

public IClams CreateClam()
{
return new FrozenClams();
}
}

#endregion

#region Pizza Stores

public abstract class PizzaStore
{
public Pizza OrderPizza(string type)
{
Pizza pizza = CreatePizza(type);
Console.WriteLine("--- Making a " + pizza.Name + " ---");

pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();

return pizza;
}

public abstract Pizza CreatePizza(string item);
}

public class NewYorkPizzaStore : PizzaStore
{
public override Pizza CreatePizza(string item)
{
Pizza pizza = null;
IPizzaIngredientFactory ingredientFactory =
new NewYorkPizzaIngredientFactory();

switch (item)
{
case "cheese":
pizza = new CheesePizza(ingredientFactory);
pizza.Name = "New York Style Cheese Pizza";
break;
case "veggie":
pizza = new VeggiePizza(ingredientFactory);
pizza.Name = "New York Style Veggie Pizza";
break;
case "clam":
pizza = new ClamPizza(ingredientFactory);
pizza.Name = "New York Style Clam Pizza";
break;
case "pepperoni":
pizza = new PepperoniPizza(ingredientFactory);
pizza.Name = "New York Style Pepperoni Pizza";
break;
}
return pizza;
}
}

public class ChicagoPizzaStore : PizzaStore
{
// Factory method implementation
public override Pizza CreatePizza(string item)
{
Pizza pizza = null;
IPizzaIngredientFactory ingredientFactory =
new ChicagoPizzaIngredientFactory();

switch (item)
{
case "cheese":
pizza = new CheesePizza(ingredientFactory);
pizza.Name = "Chicago Style Cheese Pizza";
break;
case "veggie":
pizza = new VeggiePizza(ingredientFactory);
pizza.Name = "Chicago Style Veggie Pizza";
break;
case "clam":
pizza = new ClamPizza(ingredientFactory);
pizza.Name = "Chicago Style Clam Pizza";
break;
case "pepperoni":
pizza = new PepperoniPizza(ingredientFactory);
pizza.Name = "Chicago Style Pepperoni Pizza";
break;
}
return pizza;
}
}

#endregion

#region Pizzas

public abstract class Pizza
{
protected IDough dough;
protected ISauce sauce;
protected IVeggies[] veggies;
protected ICheese cheese;
protected IPepperoni pepperoni;
protected IClams clam;

private string name;

public abstract void Prepare();

public void Bake()
{
Console.WriteLine("Bake for 25 minutes at 350");
}

public virtual void Cut()
{
Console.WriteLine("Cutting the pizza into diagonal slices");
}

public void Box()
{
Console.WriteLine("Place pizza in official Pizzastore box");
}

public string Name
{
get { return name; }
set { name = value; }
}

public override string ToString()
{
StringBuilder result = new StringBuilder();
result.Append("---- " + this.Name + " ----\n");
if (dough != null)
{
result.Append(dough);
result.Append("\n");
}
if (sauce != null)
{
result.Append(sauce);
result.Append("\n");
}
if (cheese != null)
{
result.Append(cheese);
result.Append("\n");
}
if (veggies != null)
{
for (int i = 0; i < veggies.Length; i++)
{
result.Append(veggies[i]);
if (i < veggies.Length - 1)
{
result.Append(", ");
}
}
result.Append("\n");
}
if (clam != null)
{
result.Append(clam);
result.Append("\n");
}
if (pepperoni != null)
{
result.Append(pepperoni);
result.Append("\n");
}
return result.ToString();
}
}

public class ClamPizza : Pizza
{
private IPizzaIngredientFactory _ingredientFactory;

public ClamPizza(IPizzaIngredientFactory ingredientFactory)
{
this._ingredientFactory = ingredientFactory;
}

public override void Prepare()
{
Console.WriteLine("Preparing " + this.Name);
dough = _ingredientFactory.CreateDough();
sauce = _ingredientFactory.CreateSauce();
cheese = _ingredientFactory.CreateCheese();
clam = _ingredientFactory.CreateClam();
}
}

public class CheesePizza : Pizza
{
private IPizzaIngredientFactory _ingredientFactory;

public CheesePizza(IPizzaIngredientFactory ingredientFactory)
{
this._ingredientFactory = ingredientFactory;
}

public override void Prepare()
{
Console.WriteLine("Preparing " + this.Name);
dough = _ingredientFactory.CreateDough();
sauce = _ingredientFactory.CreateSauce();
cheese = _ingredientFactory.CreateCheese();
}
}

public class PepperoniPizza : Pizza
{
private IPizzaIngredientFactory _ingredientFactory;

public PepperoniPizza(IPizzaIngredientFactory ingredientFactory)
{
this._ingredientFactory = ingredientFactory;
}

public override void Prepare()
{
Console.WriteLine("Preparing " + this.Name);
dough = _ingredientFactory.CreateDough();
sauce = _ingredientFactory.CreateSauce();
cheese = _ingredientFactory.CreateCheese();
veggies = _ingredientFactory.CreateVeggies();
pepperoni = _ingredientFactory.CreatePepperoni();
}
}

public class VeggiePizza : Pizza
{
private IPizzaIngredientFactory _ingredientFactory;

public VeggiePizza(IPizzaIngredientFactory ingredientFactory)
{
this._ingredientFactory = ingredientFactory;
}

public override void Prepare()
{
Console.WriteLine("Preparing " + this.Name);
dough = _ingredientFactory.CreateDough();
sauce = _ingredientFactory.CreateSauce();
cheese = _ingredientFactory.CreateCheese();
veggies = _ingredientFactory.CreateVeggies();
}
}

#endregion

#region Ingredients

public class ThinCrustDough : IDough
{
public override string ToString()
{
return "Thin Crust Dough";
}
}

public class ThickCrustDough : IDough
{
public override string ToString()
{
return "ThickCrust style extra thick crust dough";
}
}

public class Spinach : IVeggies
{
public override string ToString()
{
return "Spinach";
}
}

public class SlicedPepperoni : IPepperoni
{
public override string ToString()
{
return "Sliced Pepperoni";
}
}

public interface ISauce
{
string ToString();
}
public interface IDough
{
string ToString();
}
public interface IClams
{
string ToString();
}
public interface IVeggies
{
string ToString();
}
public interface ICheese
{
string ToString();
}

public interface IPepperoni
{
string ToString();
}

public class Garlic : IVeggies
{
public override string ToString()
{
return "Garlic";
}
}

public class Onion : IVeggies
{
public override string ToString()
{
return "Onion";
}
}

public class Mushroom : IVeggies
{

public override string ToString()
{
return "Mushrooms";
}
}

public class Eggplant : IVeggies
{
public override string ToString()
{
return "Eggplant";
}
}

public class BlackOlives : IVeggies
{
public override string ToString()
{
return "Black Olives";
}
}

public class RedPepper : IVeggies
{
public override string ToString()
{
return "Red Pepper";
}
}

public class PlumTomatoSauce : ISauce
{
public override string ToString()
{
return "Tomato sauce with plum tomatoes";
}
}
public class MarinaraSauce : ISauce
{
public override string ToString()
{
return "Marinara Sauce";
}
}

public class FreshClams : IClams
{

public override string ToString()
{
return "Fresh Clams from Long Island Sound";
}
}
public class FrozenClams : IClams
{
public override string ToString()
{
return "Frozen Clams from Chesapeake Bay";
}
}

public class ParmesanCheese : ICheese
{
public override string ToString()
{
return "Shredded Parmesan";
}
}

public class MozzarellaCheese : ICheese
{
public override string ToString()
{
return "Shredded Mozzarella";
}
}

public class ReggianoCheese : ICheese
{
public override string ToString()
{
return "Reggiano Cheese";
}
}
#endregion
}

通过这个例子我们可以看出抽象工厂的方法经常以工厂方法的方式实现。

实现要点

抽象工厂将产品对象的创建延迟到它的具体工厂的子类。

如果没有应对"多系列对象创建"的需求变化,则没有必要使用抽象工厂模式,这时候使用简单的静态工厂完全可以。

系列对象指的是这些对象之间有相互依赖、或作用的关系,例如游戏开发场景中的"道路"与"房屋"的依赖,"道路"与"地道"的依赖。

抽象工厂模式经常和工厂方法模式共同组合来应对"对象创建"的需求变化。

通常在运行时刻创建一个具体工厂类的实例,这一具体工厂的创建具有特定实现的产品对象,为创建不同的产品对象,客户应使用不同的具体工厂。

把工厂作为单件,一个应用中一般每个产品系列只需一个具体工厂的实例,因此,工厂通常最好实现为一个单件模式。

创建产品,抽象工厂仅声明一个创建产品的接口,真正创建产品是由具体产品类创建的,最通常的一个办法是为每一个产品定义一个工厂方法,一个具体的工厂将为每个产品重定义该工厂方法以指定产品,虽然这样的实现很简单,但它确要求每个产品系列都要有一个新的具体工厂子类,即使这些产品系列的差别很小。

优点

分离了具体的类。抽象工厂模式帮助你控制一个应用创建的对象的类,因为一个工厂封装创建产品对象的责任和过程。它将客户和类的实现分离,客户通过他们的抽象接口操纵实例,产品的类名也在具体工厂的实现中被分离,它们不出现在客户代码中。

它使得易于交换产品系列。一个具体工厂类在一个应用中仅出现一次 – 即在它初始化的时候。这使得改变一个应用的具体工厂变得很容易。它只需改变具体的工厂即可使用不同的产品配置,这是因为一个抽象工厂创建了一个完整的产品系列,所以整个产品系列会立刻改变。

它有利于产品的一致性。当一个系列的产品对象被设计成一起工作时,一个应用一次只能使用同一个系列中的对象,这一点很重要,而抽象工厂很容易实现这一点。

缺点

难以支持新种类的产品。难以扩展抽象工厂以生产新种类的产品。这是因为抽象工厂几口确定了可以被创建的产品集合,支持新种类的产品就需要扩展该工厂接口,这将涉及抽象工厂类及其所有子类的改变。

应用场景

支持多种观感标准的用户界面工具箱(Kit)。

游戏开发中的多风格系列场景,比如道路,房屋,管道等。

.NET中的应用

上文我们提到过,ADO.NET的设计中应用了抽象工厂模式。有两个类(工厂)用来构建针对不同数据库的数据访问对象(产品):DbProviderFactory和DbProviderFactories。每种不同的数据库对应一个具体的DbProviderFactory,而DbProviderFactories正是用于构建不同的DbProviderFactory的工厂的工厂。.NET中工厂类的命名都以Factory结尾。

总结

总之,抽象工厂模式提供了一个创建一系列相关或相互依赖对象的接口,运用抽象工厂模式的关键点在于应对"多系列对象创建"的需求变化。一句话,学会了抽象工厂模式,你将理解OOP的精华:面向接口编程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: