用简单工厂模式实现一个计算器类:
#include <iostream>
#include <string> using namespace std; class Operation
{
public:
Operation(double numA = , int numB = ) : numberA(numA), numberB(numB)
{
}
virtual ~Operation()
{
cout << "~Operation()" << endl;
}
virtual double GetResult()
{
double result = ;
return result;
}
protected:
double numberA;
double numberB;
}; class OperationAdd : public Operation
{
public :
OperationAdd(double numA = , int numB = ) : Operation(numA, numB)
{
}
virtual ~OperationAdd()
{
cout << "~OperationAdd()" << endl;
}
virtual double GetResult()
{
double result = ;
result = numberA + numberB;
return result;
}
};
class OperationSub : public Operation
{
public :
OperationSub(double numA = , int numB = ) : Operation(numA, numB)
{
}
virtual ~OperationSub()
{
cout << "~OperationSub()" << endl;
}
virtual double GetResult()
{
double result = ;
result = numberA - numberB;
return result;
}
}; class OperationFactory
{
public :
virtual ~OperationFactory()
{
}
static Operation* createOperate(double numA, double numB, char operate)
{
Operation* oper;
switch (operate)
{
case '+' :
oper = new OperationAdd(numA, numB);
break;
case '-' :
oper = new OperationSub(numA, numB);
break;
default :
oper = ;
break;
}
return oper;
}
}; int main()
{
Operation* oper;
oper = OperationFactory::createOperate(, , '+');
double result = oper->GetResult();
cout << result << endl;
delete oper;
return ;
}
简单工厂模式实现计算器
简单工厂模式的抽象实现:
#include <iostream> using namespace std; class Product
{
public :
Product()
{
}
~Product()
{
}
virtual void CreateProduct()
{
}
private :
//
}; class ProductA : public Product
{
public :
ProductA() : Product()
{
cout << "ProductA()" << endl;
}
~ProductA()
{
cout << "~ProductA()" << endl;
}
virtual void CreateProduct()
{
}
}; class ProductB : public Product
{
public :
ProductB() : Product()
{
cout << "ProductB()" << endl;
}
~ProductB()
{
cout << "~ProductB()" << endl;
}
virtual void CreateProduct()
{
}
}; class SimpleFactory
{
public :
static Product* Create(int type)
{
//Product *prod;
switch (type)
{
case :
prod = new ProductA;
break;
case :
prod = new ProductB;
break;
default :
prod = ;
}
return prod;
}
~SimpleFactory()
{
delete prod;
}
private :
static Product *prod;
};
Product* SimpleFactory::prod = ; int main()
{
Product* prod;
prod = SimpleFactory::Create();
return ;
}
简单工厂模式