工厂模式(C++)

来源:互联网 发布:建筑行业证书 知乎 编辑:程序博客网 时间:2024/04/24 12:52

简述

    工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现类,选择判断的问题在客户端,想要增加功能,修改客户端。而简单工厂是在内部进行逻辑判断。

场景说明

    现在有苹果和梨两种水果,而水果的生产流程复杂,所以需要水果工厂来生成。现开一个苹果工厂和梨工厂,各自生成自己的水果,当用户需要水果时,直接向工厂提出生产就可以了。不必和每个水果打交道

UML类图


对象职责

client:用户,按照自己的需求,告诉合适工厂生成水果
Plant:抽象水果
Fruits:抽象工厂
ApplePlant:苹果工厂,用户依赖苹果工厂获得苹果
Apple:苹果,用户最后得到的水果

代码实现

#include <stdio.h>#include <iostream>//抽象水果class Fruits{public:Fruits(){};virtual void show(){};private:};//苹果class Apple : public Fruits{public:Apple(){};virtual void show(){std::cout << "我是苹果" << std::endl;}private:};//梨class Pear : public Fruits{public:Pear(){};virtual void show(){std::cout << "我是梨" << std::endl;}private:};//抽象工厂class Plant{public:Plant(){};virtual Fruits* getManufactureFruits();private:};//苹果工厂class ApplePlant{public:ApplePlant(){};virtual Fruits* getManufactureFruits(){return new Apple;}private:};//梨工厂class PearPlant{public:PearPlant(){};virtual Fruits* getManufactureFruits(){return new Pear;}private:};int maingongc(){ApplePlant *applePlant = new ApplePlant;Fruits *apple = applePlant->getManufactureFruits();apple->show();PearPlant *pearPlant = new PearPlant;Fruits *pear = pearPlant->getManufactureFruits();pear->show();while (1);return 0;}