//
// main.cpp
// factory_method_pattern
//
// Created by apple on 2019/3/10.
// Copyright © 2019年 apple. All rights reserved.
//
#include <iostream>
class IProduct
{
public:
virtual void create() = 0;
virtual ~IProduct() {}
};
class Error:public IProduct
{
public:
void create()
{
std::cout<<"Error"<<std::endl;
}
};
class Box:public IProduct
{
public:
void create()
{
std::cout<<"Box"<<std::endl;
}
};
class Phone:public IProduct
{
public:
void create()
{
std::cout<<"Phone"<<std::endl;
}
};
class Pen:public IProduct
{
public:
void create()
{
std::cout<<"Pen"<<std::endl;
}
};
class IFactory
{
public:
virtual IProduct *GetProduct() = 0;
virtual ~IFactory() {}
};
class FactoryA:public IFactory
{
public:
IProduct *GetProduct();
};
class FactoryB:public IFactory
{
public:
IProduct *GetProduct();
};
IProduct *FactoryA::GetProduct()
{
return new Box();//A工厂只能生产Box
}
IProduct *FactoryB::GetProduct()
{
return new Phone();//B工厂只能生产Phone
}
int main(int argc, const char * argv[]) {
IProduct *product;
IFactory *factory;
factory= new FactoryA();
product = factory->GetProduct();
product->create();
delete product;
product = NULL;
delete factory;
factory = NULL;
factory = new FactoryB();
product = factory->GetProduct();
product->create();
delete product;
product = NULL;
delete factory;
factory = NULL;
return 0;
}
Box
Phone
Program ended with exit code: 0