令狐冲之独孤九剑篇--策略模式
策略模式《独孤九剑》在金庸小说《神雕侠侣》、《笑傲江湖》中提到 为「剑魔」独孤求败所创,以无招胜有招,杀尽仇寇,败尽英 雄,天下更无抗手,唯隐居深谷以雕为友,『呜呼!群雄束手,长剑空利,不亦悲夫!生平欲求敌手,而不可得,诚寂寥难堪也』最后埋剑空谷,茕茕了此一生。
做技术的多么渴望这种状态,慢慢磨炼自己的功夫,笔者少年也是个功夫迷,并且相信轻功的存在,学校中,反复跳上乒乓球台,锤炼轻功;村子里,来回助跑,废弃的老墙蹬倒了好几堵。
现在做技术了,这种心态还在,感觉只要不停的学习锤炼,就能疾风快马,仗剑天涯。
本系列为新编系列,通过武侠小说,《西游记》,《龙珠》等门派关系,师徒关系,功夫继承,来解释设计模式,而且代码极简,以表达设计模式的思想为主。
上一篇:请添加链接描述
场景:《独孤九剑》分为九种剑术,这里列举三种作为三种子类,这三种类都属于继承自《独孤九剑》类
Book_up <<独孤九剑>>
Book_A<<破剑术>>
Book_B<<破暗器术>>
Book_C<<破刀术>>
Fox_punching:令狐冲
: Strategy.o
g++ -o Exe Strategy.o
main.o : Strategy.cpp
g++ -g -c Strategy.cpp
clean :
rm Strategy#include <iostream>
#include <string>
using namespace std;
//策略模式
enum Type
{
A,
B,
C
};
class Book_up //<<独孤九剑>>
{
public:
virtual void show_skill() = 0;
};
class Book_A : public Book_up
{
public:
void show_skill();
};
void Book_A::show_skill()
{
cout << "Sword breaking skill" << endl;
}
class Book_B : public Book_up
{
public:
void show_skill();
};
void Book_B::show_skill()
{
cout << "Hidden weapon breaking skill" << endl;
}
class Book_C : public Book_up
{
public:
void show_skill();
};
void Book_C::show_skill()
{
cout << "knife breaking skill" << endl;
}
class Fox_punching
{
public:
Book_up* p_Bool_up = NULL; //<<独孤九剑>>
Book_A* p_Book_A = NULL; //<<破剑术>>
Book_B* p_Book_B = NULL;//<<破暗器术>>
Book_C* p_Book_C = NULL;//<<破刀术>>
void read_book(Type type);
void throw_skill();
~Fox_punching();
};
Fox_punching::~Fox_punching()
{
if(p_Book_A != NULL)
{
delete p_Book_A;
}
if(p_Book_B != NULL)
{
delete p_Book_B;
}
if(p_Book_C != NULL)
{
delete p_Book_C;
}
}
void Fox_punching::read_book(Type type)
{
if (type == A)
{
if (p_Book_A == NULL)
{
p_Bool_up = new Book_A;
}
}
if(type == B)
{
if(p_Book_B == NULL)
{
p_Bool_up = new Book_B;
}
}
if (type == C)
{
if (p_Book_C == NULL)
{
p_Bool_up = new Book_C;
}
}
}
void Fox_punching::throw_skill()
{
cout << "be careful" << endl;
p_Bool_up->show_skill();
}
int main(void)
{
//<<破剑术>>
Fox_punching* p_Fox_punching = new Fox_punching;
p_Fox_punching->read_book(Type::A);
p_Fox_punching->throw_skill();
//<<破暗器术>>
p_Fox_punching->read_book(Type::B);
p_Fox_punching->throw_skill();
//<<破刀术>>
p_Fox_punching->read_book(Type::C);
p_Fox_punching->throw_skill();
delete p_Fox_punching;
return 0;
}
</div>
<div id="asideoffset"></div>
https://blog.51cto.com/u_14338379/4593219
页:
[1]