简介

提供了接口来创建相关或者依赖的对象,而不用具体的使用new类名的方式。使用此模式封装了产品的构建,同时类的数量也会变多。

UML类图

clipboard.png

示例

曾经,日本制造代表着制造的先进水平(现在很多领域依然如此)。虎牌,象印等品牌生产的保温杯,电饭煲深受消费者的喜爱,并且消费者很关注这些产品的产地。现在,你作为他们的代理商(类似于天猫京东),销售他们的产品,满足消费者的需求。

构建产品类:
product.h

#ifndef PRODUCT_H
#define PRODUCT_H

class CVacuumCup //保温杯
{
public:
    virtual void Warm() = 0;
};

class CTigerVacuumCup:public CVacuumCup
{
public:
    virtual void Warm();
};

class CZojirushiVacuumCup:public CVacuumCup
{
public:
    virtual void Warm();
};

class CCooker //电饭煲
{
public:
    virtual void Cook() = 0;
};

class CTigerCooker:public CCooker
{
public:
    virtual void Cook();
};

class CZojirushiCooker:public CCooker
{
public:
    virtual void Cook();
};

#endif

产品实现类,product.cpp

#include <iostream>
#include "product.h"

using namespace std;

void CTigerVacuumCup::Warm()
{
    cout<<"TigerVacuumCup Warm."<<endl;
}

void CZojirushiVacuumCup::Warm()
{
    cout<<"ZojirushiVacuumCup Warm."<<endl;
}

void CTigerCooker::Cook()
{
    cout<<"TigerCooker Cook."<<endl;
}

void CZojirushiCooker::Cook()
{
    cout<<"ZojirushiCooker Cook."<<endl;
}

构建工厂类:
factory.h

#ifndef FACTORY_H
#define FACTORY_H
#include <string>
#include "product.h"

using namespace std;
class CFactory
{
public:
    CFactory(string strAddr):m_strAddr(strAddr){};
    virtual CVacuumCup* CreateVacuumCup() = 0;
    virtual CCooker* CreateCooker() = 0;
public:
    string m_strAddr;
};

class CTigerFactory:public CFactory
{
public:
    CTigerFactory(string strAddr):CFactory(strAddr){};
    CVacuumCup* CreateVacuumCup();
    CCooker* CreateCooker();
};

class CZojirushiFactory:public CFactory
{
public:
    CZojirushiFactory(string strAddr):CFactory(strAddr){};
    CVacuumCup* CreateVacuumCup();
    CCooker* CreateCooker();
};
#endif

工厂实现类,factory.cpp

#include "factory.h"

CVacuumCup* CTigerFactory::CreateVacuumCup()
{
    return new CTigerVacuumCup;
}

CCooker* CTigerFactory::CreateCooker()
{
    return new CTigerCooker;
}

CVacuumCup* CZojirushiFactory::CreateVacuumCup()
{
    return new CZojirushiVacuumCup;
}

CCooker* CZojirushiFactory::CreateCooker()
{
    return new CZojirushiCooker;
}

客户端调用,main.cpp

#include "factory.h"
#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
int main(int argc, char* argv[])
{
    //1.一个顾客想要构建中国产虎牌保温杯和电饭煲
    CFactory* pTigerFactory = new CTigerFactory("China");
    CVacuumCup* pTigerCup = pTigerFactory->CreateVacuumCup();
    CCooker* pTigerCooker = pTigerFactory->CreateCooker();

    SAFE_DELETE(pTigerCup);
    SAFE_DELETE(pTigerCooker);
    SAFE_DELETE(pTigerFactory);

    //2.另一个顾客想要日本产象印牌保温杯和电饭煲
    CFactory* pZojirushiFactory = new CZojirushiFactory("Japan");
    CVacuumCup* pZojirushiCup = pZojirushiFactory->CreateVacuumCup();
    CCooker* pZojirushiCooker = pZojirushiFactory->CreateCooker();
    
    SAFE_DELETE(pZojirushiCup);
    SAFE_DELETE(pZojirushiCooker);
    SAFE_DELETE(pZojirushiFactory);
    return 0;
}

one_piece
26 声望8 粉丝