简单的策略模式,类模版

#include "stdafx.h"
#include <iostream>
using namespace std;
template<class T>class Operation
{
public:
virtual void Algorithm() = 0;
};

template<class T>class Add:public Operation<T>
{
public:
Add (T a , T b):m_a(a),m_b(b)
{
}

void Algorithm()
{
cout<< (m_a + m_b)<<endl;
}
private:
T m_a;
T m_b;

};

template<class T>class Sub:public Operation<T>
{
public:
Sub(T a, T b):m_a(a),m_b(b)
{
}

void Algorithm()
{
cout<< (m_a - m_b)<<endl;
}
private:
T m_a;
T m_b;
};

//
template<class T>class Contex
{
public:
Contex(Operation<T>*ptr)
{
this->ptr = ptr;
}
void Algorithm()
{
ptr->Algorithm();
}
private:
Operation<T>* ptr;
};

int main()
{
int a =10;
int b = 1;
double c =10.1;
double d = 1.2;
Operation<int> *ptr = new Add<int>(a,b);
Contex<int> *contex = new Contex<int>(ptr);
contex->Algorithm();

Contex<double>*contex1 = new Contex<double>(new Sub<double>(c,d));
contex1->Algorithm();

return 0;

}

 

写的有些拙劣,主要同时为了熟悉下类模版。得搞会儿dota啦~\(≧▽≦)/~啦啦啦

posted on 2012-06-02 16:17  kunkka_  阅读(112)  评论(0编辑  收藏  举报