码迷,mamicode.com
首页 > 其他好文 > 详细

工厂方法模式

时间:2015-05-28 00:28:13      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

1】什么是工厂方法模式?

定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。

【2】工厂方法模式代码示例
#include <iostream>
#include <string>
using namespace std;

class Operation
{
public:
    double numberA;
    double numberB;

    virtual double getResult()
    {
        return 0;
    }
};

class addOperation : public Operation
{
    double getResult()
    {
        return numberA + numberB;
    }
};

 
class subOperation : public Operation
{
    double getResult()
    {
        return numberA - numberB;
    }
};

class mulOperation : public Operation
{
    double getResult()
    {
        return numberA * numberB;
    }
};

class divOperation : public Operation
{
    double getResult()
    {
        return numberA / numberB;
    }
};

class IFactory
{
public:
    virtual Operation *createOperation() = 0;
};

class AddFactory : public IFactory
{
public:
    static Operation *createOperation()
    {
        return new addOperation();
    }
};


class SubFactory : public IFactory
{
public:
    static Operation *createOperation()
    {
        return new subOperation();
    }
};

class MulFactory : public IFactory
{
public:
    static Operation *createOperation()
    {
        return new mulOperation();
    }
};

class DivFactory : public IFactory
{
public:
    static Operation *createOperation()
    {
        return new divOperation();
    }
};

int main()
{
    Operation *oper = MulFactory::createOperation();
    oper->numberA = 9;
    oper->numberB = 99;
    cout << oper->getResult() << endl;
    return 0;
}

 

工厂方法模式

标签:

原文地址:http://www.cnblogs.com/leijiangtao/p/4534644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!