用到了继承和聚合,不同的方法继承于统一的接口,方法的对象聚合于工厂中
class Operator
{
public:
Operator() {};
~Operator() {};
public:
virtual int oper()
{
return 0;
}
void set_a(double a_input)
{
a = a_input;
}
double get_a()
{
return a;
}
void set_b(double b_input)
{
b = b_input;
}
double get_b()
{
return b;
}
private:
double a;
double b;
};
class AddMethod:public Operator
{
public:
AddMethod() {};
~AddMethod() {};
public:
virtual int oper()
{
return get_a()+ get_b();
}
};
class SubMethod :public Operator
{
public:
SubMethod() {};
~SubMethod() {};
public:
virtual int oper()
{
return get_a() - get_b();
}
};
class OperatorFactory
{
public:
OperatorFactory() {};
~OperatorFactory() {};
public:
Operator* createOperator(char data)
{
switch (data)
{
case '+':
return new AddMethod();
case '-':
return new SubMethod();
}
}
};
int main()
{
OperatorFactory operFactory;
Operator* add_obj = operFactory.createOperator('+');
add_obj->set_a(10);
add_obj->set_b(5);
double value = add_obj->oper();
std::cout << value << "\n";
}
优点: 对工厂方法对比,该方法简单、所需要的文件较少,适合方法种类较为固定的问题。
缺点:违反了开闭原则,在增添新的方法的时候,需要在工厂类中添加改方法的实例;
,