产品及其子类实现
以手机加工厂开展例子
class Phone {
public:
virtual void Operation() = 0;
}
class Xiaomi : public Phone {
public:
void Operation() override {
printf("为发热而生!");
}
}
class Huawei : public Phone {
public:
void Operation() override {
printf("不买不是中国人!");
}
}
class Apple : public Phone {
public:
void Operation() override {
printf("傲视群雄!");
}
}
工厂方法的不同实现
简单工厂(一般用于初期实现)
生成的逻辑一般位于工厂之中【if…else等】,不符合开放封闭原则
class PhoneFactory{
public:
static Phone* createPhone(std::string Type){
if(Type=="小米"){
return new Xiaomi();
}else if (Type == "华为"){
return new Huawei();
}else if (Type == "苹果"){
return new Apple();
}else{
return NULL;
}
}
}
工厂方法(为每个产品子类创建一个子工厂)
符合开放封闭及单一职责
class PhoneFactory {
public:
virtual ~PhoneFactory(){}
virtual Product* FactoryMethod() const =0;
void SomeOperation() const {
Phone* phone=FactoryMethod();
phone->Operation();
delete product;
}
}
/*Concrete Creator override factory method to supply different Product Class*/
class XiaomiFactory: public PhoneFactory{
public:
Product* FactoryMethod() const override {
return new Xiaomi();
}
}
class HuaweiFactory: public PhoneFactory{
public:
Product* FactoryMethod() const override {
return new Huawei();
}
}
class AppleFactory: public PhoneFactory{
public:
Product* FactoryMethod() const override {
return new Apple();
}
}
抽象工厂(与上述两种方法无关)
主要整合多个不同的对象!
PC类
class PC{
public
virtual void Operation() = 0 ;
}
class MiPC: public PC {
public:
void Operation() override {
printf("制造小米电脑");
}
}
class MAC: public PC {
public:
void Operation() override {
printf("制造苹果电脑");
}
}
抽象工厂
class MultiFactory{
public:
Phone* phoneCreator() const =0 ;
PC* pcCreator() const = 0;
}
class XiaomiFactory : public MultiFactory{
public:
Phone* phoneCreator() const override {
return new Xiaomi();
}
PC* pcCreator() const override {
return new MiPC();
}
}
class AppleFactory : public MultiFactory{
public:
Phone* phoneCreator() const override {
return new Apple();
}
PC* pcCreator() const override {
return new MAC();
}
}