首页 > 代码库 > 抽象工厂模式之C++实现

抽象工厂模式之C++实现

 

 

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

//Product
class Water
{
public:
    virtual void AddWater() = 0;
};

class Flour
{
public:
    virtual void AddFlour() = 0;
};

class BreadWater : public Water
{
public:
    void AddWater()
    {
        cout << "ÏòÃæ°ü»úÆ÷ÖÐÌí¼ÓË®" << endl;
    }
};

class BreadFlour : public Flour
{
public:
    void AddFlour()
    {
        cout << "ÏòÃæ°ü»úÆ÷ÖÐÌí¼ÓÃæ·Û" << endl;
    }
};

class SteamedBreadWater : public Water
{
public:
    void AddWater()
    {
        cout << "ÏòÂøÍ·»úÆ÷ÖÐÌí¼ÓË®" << endl;
    }
};

class SteamedBreadFlour : public Flour
{
public:
    void AddFlour()
    {
        cout << "ÏòÂøÍ·»úÆ÷ÖÐÌí¼ÓÃæ·Û" << endl;
    }
};



//Factory
class Factory
{
public:
    virtual Water* GetWater() = 0;
    virtual Flour* GetFlour() = 0;
    virtual void GetProduct() = 0;
};

class BreadFactory : public Factory
{
public:
    Water* GetWater()
    {
        return new BreadWater;
    }

    Flour* GetFlour()
    {
        return new BreadFlour;
    }

    void GetProduct()
    {
        cout << "Ãæ°ü³ö¯!" << endl;
    }
};

class SteamedBreadFactory : public Factory
{
public:
    Water* GetWater()
    {
        return new SteamedBreadWater;
    }

    Flour* GetFlour()
    {
        return new SteamedBreadFlour;
    }

    void GetProduct()
    {
        cout << "ÂøÍ·³ö¯!" << endl;
    }
};
    

int main()
{
    Factory *pBreadFactory = new BreadFactory;
    pBreadFactory->GetFlour()->AddFlour();
    pBreadFactory->GetWater()->AddWater();
    pBreadFactory->GetProduct();

    Factory *pSteamedBreadFactory = new SteamedBreadFactory;
    pSteamedBreadFactory->GetFlour()->AddFlour();
    pSteamedBreadFactory->GetWater()->AddWater();
    pSteamedBreadFactory->GetProduct();

    free(pSteamedBreadFactory);
    free(pBreadFactory);
    return 0;
}