原版设计模式之抽象工厂模式
Intent (定义)
Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.
(提供一个接口去创建相关联或者依赖的对象,而不用指定具体的实现类)
Also Known As (又名)
Kit
Motivation (举例)
(以下是自己理解,其实英文版解释的更好)
上述是用一个软件设计的案例来的,
-
WidgetFactory: 抽象工厂,用于创建滚动条和窗口。
-
MotifWidgetFactory: 继承抽象工厂(WidgetFactory),用于给Motif类型创建滚动条和窗口。
他依赖于MotifWindow和MotifScrollBar -
PMWidgetFactory: 继承抽象工厂(WidgetFactory),用于给PM类型创建滚动条和窗口。
他依赖于PMWindow和PMScrollBar -
Client: 客户端,用来操作软件或者系统
从上面设计图可以看出,假设用代码实现,应该是如下样式,
抽象工厂案例代码
Applicability (哪些情况适合用此模式)
- a system should be independent of how its products are created, composed, and
represented. (系统是独立于产品的创建,组成,表现) - a system should be configured with one of multiple families of products. (一个系统由一个或者多个系列的产品配置而来)
- a family of related product objects is designed to be used together, and you
need to enforce this constraint. (一系列的产品是强制组合使用时。上面的案例) - you want to provide a class library of products, and you want to reveal just
their interfaces, not their implementations. (你想提供产品的类库,同时你仅仅想展示接口而不是具体实现。)
Participants (参与者–即上图类说明)
- AbstractFactory (WidgetFactory)
- declares an interface for operations that create abstract product
objects. (为创建抽象产品的操作声明一个接口)
- declares an interface for operations that create abstract product
- ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
- implements the operations to create concrete product objects. (实现要创作具体产品的操作)
- AbstractProduct (Window, ScrollBar)
- declares an interface for a type of product object. (为某类产品声明一个接口)
- ConcreteProduct (MotifWindow, MotifScrollBar)
- defines a product object to be created by the corresponding concrete
factory. (定义一个由对应的具体的工厂创建的产品对象) - implements the AbstractProduct interface. (实现抽象产品接口)
- defines a product object to be created by the corresponding concrete
- Client
- uses only interfaces declared by AbstractFactory and AbstractProduct
classes. (仅仅使用抽象工厂和抽象产品声明的接口)
- uses only interfaces declared by AbstractFactory and AbstractProduct
Collaborations (约定)
- Normally a single instance of a ConcreteFactory class is created at run-time.
This concrete factory creates product objects having a particular
implementation.
To create different product objects, clients should use a
different concrete factory.
(通常在运行时创建具体工厂的单例。
具体工厂创建拥有特殊实现的产品。
为了创建不同的产品,应该使用不同的实例化工厂。) - AbstractFactory defers creation of product objects to its ConcreteFactory
subclass. (抽象工厂将产品的创建延迟到具体的工厂子类中。)
Known Uses
InterViews uses the “Kit” suffix [Lin92] to denote AbstractFactory classes. (用Kit作为后缀表示一个抽象工厂类。)