简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码进行。由于使用了多态性,工厂方法模式保持了简单工厂模式的优点,而且克服了它的缺点。但缺点是由于每加一个产品需要加一个产品工厂的类,增加了额外的开发量。
#include <iostream>
#include <exception>
class Operation {
public:
Operation()
{
std::cout <<"this is Operation()\n";
}
virtual ~Operation()
{
std::cout <<"this is ~Operation()\n";
}
void NumberA(int a)
{
ma = a;
}
void NumberB(int b)
{
mb = b;
}
int GetNumberA()
{
return ma;
}
int GetNumberB()
{
return mb;
}
virtual int GetResult() = 0;
private:
int ma;
int mb;
};
class AddOperation : public Operation {
public:
virtual int GetResult()
{
return GetNumberA() + GetNumberB();
}
};
class SubOperation : public Operation {
public:
virtual int GetResult()
{
return GetNumberA() - GetNumberB();
}
};
class MulOperation : public Operation {
public:
virtual int GetResult()
{
return GetNumberA() * GetNumberB();
}
};
class DivOperation : public Operation {
public:
virtual int GetResult()
{
return GetNumberA() / GetNumberB();
}
};
class Factory {
public:
virtual Operation *CreateOperation() = 0;
};
class AddFactory : public Factory {
public:
Operation *CreateOperation()
{
return new AddOperation();
}
};
class SubFactory : public Factory {
public:
Operation *CreateOperation()
{
return new SubOperation();
}
};
class MulFactory : public Factory {
public:
Operation *CreateOperation()
{
return new MulOperation();
}
};
class DivFactory : public Factory {
public:
Operation *CreateOperation()
{
return new DivOperation();
}
};
int main()
{
Factory *p = new AddFactory();
Operation *p1 = p->CreateOperation();
p1->NumberA(10);
p1->NumberB(20);
std::cout << p1->GetResult() << std::endl;
delete p1;
return 0;
}