首页 > 代码库 > 策略模式之C++实现
策略模式之C++实现
#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
typedef enum
{
XIANG_LONG_SHI_BA_ZHANG = 1,
DA_GOU_GUN_FA = 2,
} WU_GONG_EN;
//大侠一次可以使用一种武功,但是武功种类繁杂
class Daxia
{
protected:
string name;
public:
Daxia(string name)
{
this->name = name;
}
virtual void WuGong() = 0;
};
class XiangLongShiBaZhang : public Daxia
{
public:
XiangLongShiBaZhang(string name) : Daxia(name) {}
void WuGong()
{
cout << this->name << "使用降龙十八掌" << endl;
}
};
class DaGouGunFa : public Daxia
{
public:
DaGouGunFa(string name) : Daxia(name) {}
void WuGong()
{
cout << this->name << "使用打狗棍法" << endl;
}
};
//习武厅必须保存一个大侠对象
class XiWuTing
{
public:
Daxia *daxia;
public:
XiWuTing(string name, WU_GONG_EN zhaoshi)
{
switch(zhaoshi)
{
case XIANG_LONG_SHI_BA_ZHANG:
daxia = new XiangLongShiBaZhang(name);
break;
case DA_GOU_GUN_FA:
daxia = new DaGouGunFa(name);
break;
default:
daxia = NULL;
break;
}
}
void LianGong()
{
daxia->WuGong();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
XiWuTing *xiwuting = new XiWuTing("郭靖", DA_GOU_GUN_FA);
xiwuting->LianGong();
return 0;
}
#include <string>
#include <vector>
#include <iostream>
using namespace std;
typedef enum
{
XIANG_LONG_SHI_BA_ZHANG = 1,
DA_GOU_GUN_FA = 2,
} WU_GONG_EN;
//大侠一次可以使用一种武功,但是武功种类繁杂
class Daxia
{
protected:
string name;
public:
Daxia(string name)
{
this->name = name;
}
virtual void WuGong() = 0;
};
class XiangLongShiBaZhang : public Daxia
{
public:
XiangLongShiBaZhang(string name) : Daxia(name) {}
void WuGong()
{
cout << this->name << "使用降龙十八掌" << endl;
}
};
class DaGouGunFa : public Daxia
{
public:
DaGouGunFa(string name) : Daxia(name) {}
void WuGong()
{
cout << this->name << "使用打狗棍法" << endl;
}
};
//习武厅必须保存一个大侠对象
class XiWuTing
{
public:
Daxia *daxia;
public:
XiWuTing(string name, WU_GONG_EN zhaoshi)
{
switch(zhaoshi)
{
case XIANG_LONG_SHI_BA_ZHANG:
daxia = new XiangLongShiBaZhang(name);
break;
case DA_GOU_GUN_FA:
daxia = new DaGouGunFa(name);
break;
default:
daxia = NULL;
break;
}
}
void LianGong()
{
daxia->WuGong();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
XiWuTing *xiwuting = new XiWuTing("郭靖", DA_GOU_GUN_FA);
xiwuting->LianGong();
return 0;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。