C语言和设计模式(工厂方法模式)

文章目录

一句话理解

工厂中每个产品自己实现自己的创建函数,工厂只提供函数指针(虚函数)
优点:将工厂和每个产品之间的耦合解决掉,每次增加产品,不需要修改工厂内部代码

例子

#include <iostream>
using namespace std;

class Product
{
public:
    virtual void Show() = 0;
};

class ProductA : public Product
{
public:
    void Show()
    {
        cout<< "I'm ProductA"<<endl;
    }
};

class ProductB : public Product
{
public:
    void Show()
    {
        cout<< "I'm ProductB"<<endl;
    }
};

class Factory
{
public:
    virtual Product *CreateProduct() = 0;
};

class FactoryA : public Factory
{
public:
    Product *CreateProduct()
    {
        return new ProductA ();
    }
};

class FactoryB : public Factory
{
public:
    Product *CreateProduct()
    {
        return new ProductB ();
    }
};

int main(int argc , char *argv [])
{
    Factory *factoryA = new FactoryA ();
    Product *productA = factoryA->CreateProduct();
    productA->Show();

    Factory *factoryB = new FactoryB ();
    Product *productB = factoryB->CreateProduct();
    productB->Show();

    if (factoryA != NULL)
    {
        delete factoryA;
        factoryA = NULL;
    }

    if (productA != NULL)
    {
        delete productA;
        productA = NULL;
    }

    if (factoryB != NULL)
    {
        delete factoryB;
        factoryB = NULL;
    }

    if (productB != NULL)
    {
        delete productB;
        productB = NULL;
    }
    return 0;
}
发布了297 篇原创文章 · 获赞 6 · 访问量 8488

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/103551134