你的Creator
班级就是工厂。让我们称它为ProductFactory
,以便使示例更明确。
(我假设您使用的是 C++)
class Book : public Product
{
};
class Computer : public Product
{
};
class ProductFactory
{
public:
virtual Product* Make(int type)
{
switch (type)
{
case 0:
return new Book();
case 1:
return new Computer();
[...]
}
}
}
像这样称呼它:
ProductFactory factory = ....;
Product* p1 = factory.Make(0); // p1 is a Book*
Product* p2 = factory.Make(1); // p2 is a Computer*
// remember to delete p1 and p2
所以,回答你的问题:
它与子类有什么关系?我应该使用子类做什么?
工厂模式的定义是说工厂定义了一个通用 API 来创建某种类型的实例(通常是接口或抽象类),但返回的实现的真实类型(因此子类引用)是工厂。在示例中,工厂返回Product
实例,其中Book
和Computer
是有效的子类。
工厂还有其他成语,比如工厂的 API 和工厂的具体实现在我的示例中不接受type
类似,但它们与返回的实例类型相结合,如下所示:
class ProductFactory
{
public:
virtual Product* Make() = 0;
}
class BookProductFactory : public ProductFactory
{
public:
virtual Product* Make()
{
return new Book();
}
}
在这个类中BookProductFactory
总是返回Book
实例。
ProductFactory* factory = new BookProductFactory();
Product* p1 = factory->Make(); // p1 is a Book
delete p1;
delete factory;
为了清楚起见,由于Abstract Factory
和Factory method
设计模式之间似乎有些混淆,让我们看一个具体的例子:
使用抽象工厂
class ProductFactory {
protected:
virtual Product* MakeBook() = 0;
virtual Product* MakeComputer() = 0;
}
class Store {
public:
Gift* MakeGift(ProductFactory* factory) {
Product* p1 = factory->MakeBook();
Product* p2 = factory->MakeComputer();
return new Gift(p1, p2);
}
}
class StoreProductFactory : public ProductFactory {
protected:
virtual Product* MakeBook() { return new Book(); }
virtual Product* MakeComputer() { return new Computer(); }
}
class FreeBooksStoreProductFactory : public StoreProductFactory {
protected:
virtual Product* MakeBook() {
Book* b = new FreeBook(); // a FreeBook is a Book with price 0
return b;
}
}
这是这样使用的:
Store store;
ProductFactory* factory = new FreeBooksStoreProductFactory();
Gift* gift = factory->MakeGift(factory);
// gift has a FreeBook (Book with price 0) and a Computer
delete gift;
delete factory;
使用工厂方法
class Store {
public:
Gift* MakeGift() {
Product* p1 = MakeBook();
Product* p2 = MakeComputer();
return new Gift(p1, p2);
}
protected:
virtual Product* MakeBook() {
return new Book();
}
virtual Product* MakeComputer() {
return new Computer();
}
}
class FreeBooksStore : public Store {
protected:
virtual Product* MakeBook() {
Book* b = new FreeBook(); // a FreeBook is a Book with price 0
return b;
}
}
这是这样使用的:
Store* store = new FreeBooksStore();
Gift* gift = store->MakeGift();
// gift has a FreeBook (Book with price 0) and a Computer
delete gift;
delete store;
当您type
像我在原始示例中那样使用鉴别器时,我们正在使用parametized factory methods
- 一种知道如何创建不同类型对象的方法。但这可以以一个Abstract Factory
或Factory Method
模式出现。一个小技巧:如果你正在扩展你正在使用抽象工厂的工厂类。如果您使用创建方法扩展类,那么您使用的是工厂方法。