设计模式读书笔记:Factory Method(工厂方法)
2015-07-03 11:28:46
意图:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
结构图:来自《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/FactoryMethod
Creator
namespace NS_FACTORY_METHOD {
class Product;
class Creator {
public:
Creator() {}
virtual ~Creator() {}
virtual Product *createProduct(void) = 0;
};
template <class TheProduct>
class StandardCreator : public Creator {
public:
StandardCreator() {}
virtual ~StandardCreator() {}
virtual Product *createProduct(void);
};
template <class TheProduct>
Product *StandardCreator<TheProduct>::createProduct(void) {
return new TheProduct;
}
} /* namespace NS_FACTORY_METHOD */
Product
namespace NS_FACTORY_METHOD {
class Product {
public:
Product() {}
virtual ~Product() {}
virtual void printSelf(void) = 0;
};
} /* namespace NS_FACTORY_METHOD */
ConcreteProduct
#include <iostream>
#include "Creator.h"
#include "Product.h"
namespace NS_FACTORY_METHOD {
class ConcreteProduct : public Product
{
public:
ConcreteProduct() {}
virtual ~ConcreteProduct() {}
virtual void printSelf(void)
{
std::cout << "ConcreteProduct" << std::endl;
}
};
StandardCreator<ConcreteProduct> ConcreteCreator;
} /* namespace NS_FACTORY_METHOD */
main
#include "FactoryMethod/ConcreteProduct.h"
using namespace NS_FACTORY_METHOD;
int main(void)
{
Product *product = ConcreteCreator.createProduct();
product->printSelf();
delete product;
}
附加: