ڼС
梦回起点
做你害怕做的事,你会发现:不过如此
本站基于WordPress—主题by 设计窝
冀ICP备15003737号
梦回起点
Copyright © 2015-2024 All rights reserved.

工厂模式——大话设计模式读书笔记

今天看代理模式。

工厂方法模式(Factory Method): 定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化推迟到其子类。

工厂模式

下面是C++实现的代码:

/*
* initm.com
* 作者:Stupid
* 时间:2017-10-22 14:16
* 描述: 代码使用QT5.9+MinGW53_32编译通过,代码为代理模式的基本结构代码。
*/
#include <QCoreApplication>
#include <iostream>

class Operation
{
protected:
    double numberA;
    double numberB;
public:
    virtual void SetNumberA(decltype(numberA) numberA){ this->numberA = numberA; }
    virtual decltype(numberA) GetNumberA(){return numberA;}
    virtual void SetNumberB(decltype(numberB) numberB){ this->numberB = numberB; }
    virtual decltype(numberA) GetNumberB(){return numberB;}
    virtual decltype(numberA * numberB) GetResult() = 0;
};

class AddOperation: public Operation
{
public:
    decltype(numberA + numberB) GetResult()override final{
        return numberA + numberB;
    }
};

class SubOperation: public Operation
{
public:
    decltype(numberA - numberB) GetResult()override final{
        return numberA - numberB;
    }
};

class MulOperation: public Operation
{
public:
    decltype(numberA * numberB) GetResult()override final{
        return numberA * numberB;
    }
};

class DivOperation: public Operation
{
public:
    decltype(numberA / numberB) GetResult()override final{
        return numberA / numberB;
    }
};

class Factory
{
public:
    virtual Operation* CreateOperation() = 0;
};

class AddFactory: public Factory
{
public:
    Operation* CreateOperation()override final{
        return new AddOperation();
    }
};

class SubFactory: public Factory
{
public:
    Operation* CreateOperation()override final{
        return new SubOperation();
    }
};

class MulFactory: public Factory
{
public:
    Operation* CreateOperation()override final{
        return new MulOperation();
    }
};

class DivFactory: public Factory
{
public:
    Operation* CreateOperation()override final{
        return new AddOperation();
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Factory* pFactory = new AddFactory;
    Operation* pOperation = pFactory->CreateOperation();
    pOperation->SetNumberA(10);
    pOperation->SetNumberB(20);
    std::cout << pOperation->GetResult() << std::endl;

    return a.exec();
}

工厂模式相对简单工厂模式有点在于更符合开放封闭原则,加入新建一个新的类型的运算,那么我们不用改动现有工厂类和运算类,只要增加新类就可以了。而简单工厂模式需要修改工厂类。

2017-10-22
                         
暂无评论

发表回复