工厂方法模式定义了一个用于创建对象的接口,让子类决定要实例化哪一个类,也就是说工厂模式让实例化推迟到子类。
2.UML类图 3.代码实现#include
#include
using namespace std;
class Operation
{
public:
double numberA, 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;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)