标签:c++ 设计模式
#include "stdafx.h"
#include <memory>
using namespace std;
class Method
{
private :
int _Num1;
int _Num2;
public :
Method( int number1 = 0, int number2 = 0)
:_Num1( number1), _Num2( number2)
{}
virtual ~Method()
{}
int GetNum1(){ return _Num1; }
int GetNum2(){ return _Num2; }
void SetNum1( int number1){ _Num1 = number1; }
void SetNum2( int number2){ _Num2 = number2; }
virtual int Operator() = 0;
};
class AddMethod :public Method
{
public :
AddMethod( int number1 = 0, int number2 = 0) :
Method( number1, number2)
{}
virtual int Operator()
{
return GetNum1() + GetNum2();
}
};
class SubMethod :public Method
{
public :
SubMethod( int number1 = 0, int number2 = 0) :
Method( number1, number2)
{}
virtual int Operator()
{
return GetNum1() - GetNum2();
}
};
class Factory
{
public :
virtual shared_ptr <Method > Produce() = 0;
};
class AddFactory :public Factory
{
public :
virtual shared_ptr <Method > Produce()
{
return shared_ptr <Method >(new AddMethod ());
}
};
class SubFactory :public Factory
{
public :
virtual shared_ptr <Method > Produce()
{
return shared_ptr <Method >(new SubMethod ());
}
};
// FcatoryMethodPattern.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "FactoryMethod.h"
#include <memory>
#include <iostream>
using namespace std;
int _tmain (int argc , _TCHAR * argv [])
{
shared_ptr <Factory > pOperFactory( new AddFactory());
shared_ptr <Method > pMethod = pOperFactory->Produce();
pMethod->SetNum1(10);
pMethod->SetNum2(2);
int result = pMethod->Operator();
cout << pMethod->GetNum1() << "+" << pMethod->GetNum2() << "=" << result << endl;
shared_ptr <Factory > pOperFactory2( new SubFactory());
pMethod = pOperFactory2->Produce();
pMethod->SetNum1(10);
pMethod->SetNum2(2);
result = pMethod->Operator();
cout << pMethod->GetNum1() << "-" << pMethod->GetNum2() << "=" << result << endl;
getchar();
return 0;
}
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/26377223