目录
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。

定义工厂方法所创建的对象的接口。
实现Product接口。
声明工厂发法,该方法返回一个Product类型的对象。Creator也可以定义一个工厂方法的缺省实现,它返回一个缺省的ConcreteProduct对象。
可以调用工厂方法以创建一个Product对象。
重定义工厂方法以返回一个ConcreteProduct实例。
- #include
- using namespace std;
-
- class Product {
- public:
- virtual void ShowInformation() = 0;
- };
-
- class Product_A : public Product {
- public:
- void ShowInformation() {
- cout << "Product_A Information" << endl;
- }
- };
-
- class Product_B : public Product {
- public:
- void ShowInformation() {
- cout << "Product_B Information" << endl;
- }
- };
-
- class Factory {
- public:
- virtual Product* CreateProduct() = 0;
- };
-
- class Factory_A : public Factory {
- public:
- Product* CreateProduct() {
- return new Product_A();
- }
- };
-
- class Factory_B : public Factory {
- public:
- Product* CreateProduct() {
- return new Product_B();
- }
- };
-
- int main() {
-
- Factory* FactoryA = new Factory_A();
- Product* ProductA = FactoryA->CreateProduct();
- ProductA->ShowInformation();
-
- Factory* FactoryB = new Factory_B();
- Product* ProductB = FactoryB->CreateProduct();
- ProductB->ShowInformation();
-
- return 0;
- }