工厂方法模式(Factory Method)

工厂方法模式的作用:将实例的生成交给子类。
在Factory Method方法模式中,父类决定实例的生成方式,但是并不决定要生成的具体的类,具体的处理全部交给子类负责。这样就可以将生成实例的框架和实际负责生成实例的类解耦合。
示例代码如下:

#include<iostream>
using namespace std;



//简单工厂--Factory

//工厂角色、 抽象产品角色 、具体的产品角色


class Fruit
{
public:
    virtual void GetFruit()
    {
        cout<<"Fruit::GetFruit()"<<endl;
    }

    virtual ~Fruit(){}
};

class Pear:public Fruit
{
public:
    virtual void GetFruit()//采摘水果
    {
        cout<<"Pear::GetFruit()"<<endl;
    }
};


class Banana:public Fruit
{
public:
    virtual void GetFruit()//采摘水果
    {
        cout<<"Banana::GetFruit()"<<endl;
    }
};

class Factory
{
public:
    Fruit* Create(const char* name)//Fruit与Factory的这种关系就叫做依赖
    {//简单工厂的创建工作业务逻辑
        if(!strcmp(name,"Pear"))
        {
            return new Pear();
        }
        else if(!strcmp(name,"Banana"))
        {
            return new Banana();
        }
        return NULL;
    }
};



int main()
{

    Factory *pFactory=NULL;
    Fruit   *pFruit=NULL;

    pFactory=new Factory();
    pFruit  =new Fruit();

    //创建一个梨子
    pFruit=pFactory->Create("Pear");
    pFruit->GetFruit();
    delete pFruit;

    //创建一个香蕉
    pFruit=pFactory->Create("Banana");
    pFruit->GetFruit();
    delete pFruit;
    delete pFactory;

    return 0;
}

//破坏了开放封闭原则

//优缺点
//工厂类是整个模式的关键所在。它包含了必要的判断逻辑,能够根据外界的信息,
//决定究竟应该创建哪个具体类的对象。

执行上述程序,运行结果如下图所示:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值