抽象工厂模式介绍--并用C++简单实现

抽象工厂模式介绍

抽象工厂模式是一种创建型设计模式,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。它允许客户端使用抽象接口来创建一组相关的对象,而不必关心它们的具体实现。

抽象工厂模式通常用于以下情况:

  • 系统需要独立于它的产品的创建、组合和表示时。
  • 系统需要由多个系列中的一个来配置时。
  • 需要强调一组相关产品对象的设计以便进行联合使用时。
  • 提供一个产品类库,而只想显示它们的接口而不是实现时。

C++代码具体实现

#include <iostream>

class Fruit{
public:
    virtual ~Fruit(){}
    virtual void color() = 0;
};

class Apple : public Fruit{
public:
    void color() override{
        std::cout << "Apple::pink" << std::endl;
    }
};

class Orange : public Fruit{
public:
    void color() override{
        std::cout << "Orange::yellow" << std::endl;
    }
};

class Vegetable{
    public:
        virtual~Vegetable(){}
        virtual void size() = 0;
};

class Cucumber : public Vegetable{
    public:
    void size() override{
        std::cout << "12px" << std::endl;
    }
};

class Tomato : public Vegetable{
    public:
        void size() override{
            std::cout << "10px" << std::endl;
        }
};

class Factory{
public:
    virtual ~Factory(){}
    virtual Fruit* createFruit() = 0;
    virtual Vegetable* createVegetable() = 0;
};

class FactoryA : public Factory{
    public:
        Fruit* createFruit(){
            return new Apple();
        }

        Vegetable* createVegetable(){
            return new Cucumber();
        }
};

class FacotryB : public Factory{
    public:
        Fruit* createFruit(){
            return new Orange();
        }

        Vegetable* createVegetable(){
            return new Tomato();
        }
};

int main(int argc, char* argv[]){
    Factory* factory1 = new FactoryA();
    Fruit* apple = factory1->createFruit();
    Vegetable* cucumber = factory1->createVegetable();

    apple->color();
    cucumber->size();


    delete factory1;
    delete apple;
    delete cucumber;

    Factory* factory2 = new FacotryB();
    Fruit* orange = factory2->createFruit();
    Vegetable* tomato = factory2->createVegetable();
    orange->color();
    tomato->size();

    delete factory2;
    delete orange;
    delete tomato;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

telllong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值