//C++常用算法和设计模式
//第一课 常用排序算法
#include <iostream>
#include <vector>
#include <time.h>
#include <algorithm>
#include <list>
using namespace std;
//merge
struct MyPrint01
{
void operator()(int val)
{
cout << "val:" << val;
}
};
struct MyCompare01
{
bool operator()(int a, int b)
{
return a > b;
}
};
void test01()
{
vector<int> v1;
vector<int> v2;
srand(unsigned int)time(NULL);
for (int i = 0; i < 10; i++)
{
v1.push_back(rand() % 10);
}
for (int i = 0; i < 10; i++)
{
v2.push_back(rand() % 10);
}
//默认从小到大,改为从大到小
sort(v1.begin(), v1.end(),MyCompare01());
sort(v2.begin(), v2.end(),MyCompare01());
vector<int> v3;
v3.resize(v1.size() + v2.size());
//默认从小到大
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin(),MyCompare01());
for_each(v3.begin(), v3.end(), MyPrint01());
}
//random_shuffle
void testo2()
{
//打乱排序
vector<int> v;
for (int i = 0; i < 9; i++)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), MyPrint01());
cout << endl;
random_shuffle(v.begin(), v.end());
for_each(v.begin(), v.end(), MyPrint01());
cout << endl;
}
//reverse
reverse(v.begin(), v.end());
//copy swap
vector<int> v2;
v2.resize(v1.size());
copy(v1.begin(), v1.end(), v2.begin());
swap(v3, v2);//两个容器
//replace replace_if
replace(v1.begin(), v1.end(), 5, 199);//5替换成199
struct MyCompare02
{
bool operator()(int val)
{
return val > 5;
}
};
repace_if(v1.begin(), v1.end(),Mycompare02(),200);//大于5的替换
//求和
int ret = accumulate(v.begin(), v.end(), 0);
//fill
vector<int> v2;
v2.resize(10);
fill(v2.begin(),v2.end(),10);
//第二课 综合案例
/*
第一步:创建24个学生,因为每个学生都有参赛编号,参赛编号唯一,放到map中,
key是编号value选手对象
vector<int> v1;
vector<int> v2;
vector<int> v3;
*/
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
class Player
{
public:
string mName;
int mScore[3];
};
void mian(void)
{
//定义map容器,根据编号保存选手信息
map<int, Player> mPlist;
vector<int> v1;
vector<int> v2;
vector<int> v3;
vector<int> v4;
}
//面向对象的设计原则
/*
1.可维护性,可复用性;
2.原则目的:高内聚,低耦合
原则表:
1,单一职责原则
2,开闭原则:类的改动是增加代码进行,而不是修改原代码
3.里式代换原则:任何抽象类出现的地方都可以用他的实现类进行替换,
实际就是虚拟机制,语言级别实现面向对象功能;
4.依赖倒置原则:依赖于抽象接口,不要依赖于具体的实现类,也就是针对接口编程;
5,接口隔离原则:不应该强迫用户的程序依赖他们不需要的接口方法,一个接口应该只提供
一种对外功能,不应该把所有操作都封装到一个接口中。
6,合成复用原则:如果使用继承,会导致父类的任何变换都可能影响子类的行为,
如果使用对象组合,就降低了这种依赖关系,对于继承和组合,优先使用组合;
7,迪米特原则:一个对象应当对其他对象尽可能少的了解,从而降低各个对象
之间的耦合,提高系统的可维护性。例如:在一个程序中,各个模块之间相互调用,通常会
提供一个统一的接口来实现,这样其他模块不需要了解另一个模块的内部实现细节,
这样当一个模块内部的实现细节发生变化时,不会影响到其他模块的使用。(黑盒原理)
*/
/*
回答以下问题:
1.如何将代码分散在几个不同的类中?
2.为什么要有接口?
3.何谓针对抽象编程?
4,何时不应该使用继承?
5,如何不修改源代码增加新功能?
6,更好地阅读和理解现有的类库和其他系统中的源码;
*/
/*开闭原则,对扩展开放,对修改关闭。
增加功能是通过增加代码来实现的,而不是修改原代码*/
//计算器类
class calculator
{
void getResult(int a, int b, String str)
{
if (str == "+")
{
return a + b;
}
else if
{
}
else
{
}
}
};
//以上如果需要增加新的运算,则需要对代码修改,不符合扩展开放,修改闭合的
//原则,按照如下方法修改;
//写一个抽象类
class AbstractCalculator
{
public:
virtual int getResult() = 0;
};
//加法计算器
class PlusCalculator : public AbstractCalculator
{
public:
PlusCalculator();
~PlusCalculator();
void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA + mB;
}
private:
int mA;
int mB;
};
//减法计算器。。。
void test01()
{
AbstractCalculator *calculator = new PlusCalculator;
calculator->setOperatorNumber(11, 22);
calculator->getResult();
delete calculator;
//AbstractCalculator *calculator = new SubCalculator;
//calculator->getResult();
}
//迪米特法则:知道最少原则,最少知识原则
//即不需要具体的细节,只提供中间层即可
class AbstractBuilding
{
public:
virtual void sale() = 0;
virtual string getQuality() = 0;
};
//楼盘A
class BuildingA : public AbstractBuilding
{
public:
BuildingA()
{
mQulity = "优质盘";
}
void sale()
{
}
virtual string getQuality()
{
return mQulity;
}
public:
string mQulity;
};
class BuildingB : public AbstractBuilding
{
public:
BuildingB()
{
mQulity = "低质盘";
}
void sale()
{
}
virtual string getQuality()
{
return mQulity;
}
public:
string mQulity;
};
//客户端
void test0()
{
BuildingA *a = new BuildingA;
if (a->mQulity == "低质盘")
{
a->sale();
}
BuildingB *b = new BuildingB;
if (b->mQulity == "低质盘")
{
b->sale();
}
}
//中介类
class Mediator
{
public:
Mediator()
{
AbstractBuilding *building = new BuildingA;
vBuilding.push_back(building);
building = new BuildingB;
vBuilding.push_back(building);
}
//对外提供接口
AbstractBuilding* findMyBuilding(string quality)
{
for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++)
{
if ((*it)->getQuality() == quality)
{
return *it;
}
return NULL;
}
}
~Mediator()
{
for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++)
{
if (*it != NULL)
{
delete *it;
}
}
}
public:
vector<AbstractBuilding*> vBuilding;
};
void test02()
{
Mediator *mediator = new Mediator;
AbstractBuilding *building = mediator->findMyBuilding("高品质");
if (building != NULL)
{
building->sale();
}
else
{
cout << "没有符合要求的楼盘" << endl;
}
}
//合成复用原则:优先使用组合
class Person
{
public:
void setCar(AbstractCar *car)
{
this->car = car;
}
void doufeng()
{
this->car->run();
}
~Person()
{
if (this->car != NULL)
{
delete this->car;
this->car = NULL;
}
}
public:
AbstractCar *car;
};
class AbstractCar
{
public:
virtual void run() = 0;
};
class Dazhong : public AbstractCar
{
public:
virtual void run()
{
}
void doufeng()
{
}
};
//class BMW : public AbstractCar
void test
{
Person *p = new Person;
p->setCar(new Dazhong);
p->doufeng();
Person *p = new Person;
p->setCar(new BMW);
p->doufeng();
delete p;
}
//依赖倒置原则
//传统的过程式设计倾向于使高层次的模块依赖于低层次的模块,抽象层依赖于具体的层次;
//传统的设计模式通常是自顶向下的逐级依赖,这样,底层模块,中间层模块和高层模块的耦合度极高,
//若任意修改其中之一,会导致多处的修改;
//银行工作人员
class BankWorker
{
public:
void saveService()
{
cout << "办理存款业务:" << endl;
}
void payService()
{
cout << "办理支付业务" << endl;
}
void tranferService()
{
cout << "办理转账业务" << endl;
}
};
//中间层
void doSaveBussiness(BankWorker *worker)
{
worker->saveService();
}
void doTransferBussiness(BankWorker* worker)
{
worker->transferService();
}
void doPayBussiness(BankWorker* worker)
{
worker->doPayService();
}
void test01()
{
BankWorker *worker = new BankWorker;
doSaveBusiness(worker);
doPayBusiness(worker);
doTransferBusiness(worker);
}
//以上依赖严重,修改如下:依赖于抽象层
class AbstractWorker
{
public:
virtual void doBusiness() = 0;
};
//专门负责办理存款业务的工作人员
class SaveBankWorker : public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理存款业务的" << endl;
}
};
//专门办理支付的工作人员
class PayBankWorker : public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理支付业务的" << endl;
}
};
class transferBankWorker : public AbstractWorker
{
public:
virtual void doBusiness()
{
cout << "办理转账业务的" << endl;
}
};
//中层业务模块
void doNewBusiness(AbstractWorker *worker)
{
worker->doBusiness();
}
void test01()
{
AbstractWork *transfer = new transferBankWorker;
doNewBusiness(transfer);
doNewBusiness(new PayBankWorker);
doNewBusiness(new SaveBankWorker);
}
/*
工厂模式:
自己在写业务函数或者类创建的对象时,我不想创建,
只想直接使用,可以采用工厂模式来实现;
class Factory -- creatObject()
传入参数,让工厂知道应该创建什么类型的对象;
优点:
1.客户端和具体类实现类解耦
2.对于某些对象创建过程比较复杂情况,我们不用考虑这些;
注意:
1,简单工厂模式,增加新的功能是通过修改源代码实现的,不符合开闭原则;
2,类的职责过重,这个类发生问题的话,会影响很多使用这个类的模块;
*/
//simple factory
class AbstractFruit
{
public:
virtual void showName() = 0;
};
//apple
class Apple : public AbstractFruit
{
public:
virtal void showName()
{
cout << "i am an apple";
}
};
class Banana : public AbstractFruit
{
public:
virtal void showName()
{
cout << "i am an banana";
}
};
//fruit factory
class FruitFactory
{
public:
//static method
static AbstractFruit* CreatFruit(string flag)
{
if (flag == "apple")
{
return new Apple;
}
else if (flag == "banana")
{
return new Banana;
}
else
{
return NULL;
}
}
};
void test01()
{
FruitFactory *factory = new FruitFactory;
AbstractFruit *fruit = factory->CreatFruit("apple");
fruit->showName();
delete fruit;
fruit = factory->CreatFruit("banan");
fruit->showName();
delete fruit;
}
/*
简单工厂模式存在缺点,因此需要作改进;
1.抽象工厂-具体工厂-具体的产品
问题:
1.类的个数成倍增加,类越来越多,增加维护成本;
好处:符合开闭原则
抽象产品角色:
1.工厂方法模式所创建的所有对象的父类,他负责描述所有实例所公有的公共接口;
2.具体产品:工厂方法模式所创建的具体实例对象;
简单工厂模式 + 开闭原则 = 工厂方法模式
工厂方法模式的优缺点:
优点:
1.不需要记住所有类型,甚至具体参数都不用记忆;
2.实现了对象创建和使用的分离;
3.系统的可扩展性也就变得非常好,无需修改接口和原类;
缺点:
1.增加系统中类的个数,复杂度和理解度增加;
2.增加系统的抽象性和理解难度;
*/
//abstract factory
class AbstractFruitFactory
{
public:
virtual AbstractFruit* CreatFruit() = 0;
};
//apple factory
class AppleFactory : public AbstractFruitFactory
{
public:
virtual AbstractFruit* CreatFruit()
{
return new Apple;
}
};
//banan factory
class BananaFactory : public AbstractFruitFactory
{
public:
virtual AbstractFruit* CreatFruit()
{
return new Banana;
}
};
void test11()
{
AbstractFruitFactory *factory = NULL;
AbstractFruit *fruit = NULL;
//creat apple factory
factory = new AppleFactory;
fruit = factory->CreatFruit();
fruit->showName();
delete fruit;
delete factory;
}
/*
简单工厂模式的适用场景:
1.工厂类负责创建的类对象比较少,由于创建的对象比较少,不会造成工厂方法中的业务逻辑太复杂;
2.客户端只知道传入工厂类的参数,对于如何创建对象并不关心;
工厂方法适用场景:
1.客户端不知道他所需要对象的类;
2.抽象工厂类通过其子类来指定创建哪个对象;
抽象工厂模式:
1.工厂方法模式通过引入工厂等级结构,解决了简单工厂模式中工厂类职责太重的问题,
但由于工厂方法模式中每个工厂只生产一类产品,可能会导致系统中存在大量的工厂类,
势必会增加系统的开销。此时,我们可以考虑将一些相关的产品组成一个“产品族”,
由同一个工厂来统一生产,这就是我们本文将要学习的抽象工厂模式的基本思想;
*/
//abstract factory
//abstract apple
class AbstractApple
{
public:
virtual void ShowName() = 0;
};
class ChinaApple : public AbstractApple
{
public:
virtual void ShowName()
{
cout << "chinaapple";
}
};
class JapanApple : public AbstractApple
{
public:
virtual void ShowName()
{
cout << "Japanapple";
}
};
class AbstractBanana
{
public:
virtual void ShowName() = 0;
};
//class ChinaBanana
class ChinaBanana : public AbstractBanana
{
public:
virtual void ShowName()
{
cout << "China Banana";
}
};
class JapanBanana : public AbstractBanana
{
public:
virtual void ShowName()
{
cout << "Japan Banana";
}
};
//abstract factory to product family
class AbstractFactory
{
public:
virtual AbstractApple* CreatApple() = 0;
virtual AbstractBanana* CreatBanana() = 0;
virtual AbstractPear* CreatPear() = 0;
};
//china factory
class ChinaFactory : public AbstractFactory
{
public:
virtual AbstractApple* CreatApple()
{
return new ChinaApple;
}
virtual AbstractBanana* CreatBanana()
{
return new ChinaBanana;
}
virtual AbstractPear* CreatePear()
{
return new ChinaPear;
}
};
//Japan factory
class JapanFactory : public AbstractFactory
{
public:
virtual AbstractApple* CreatApple()
{
return new JapanApple;
}
virtual AbstractBanana* CreatBanana()
{
return new JapanBanana;
}
virtual AbstractPear* CreatePear()
{
return new JapanPear;
}
};
void test11()
{
AbstractFactory *factory = NULL;
AbstractApple* apple = NULL;
AbstractPear* pear = NULL;
AbstractBanana* banana = NULL;
//china factory
factory = new ChinaFactory;
apple = factory->CreatApple();
pear = factory->CreatPear();
banana = factory->CreatPear();
apple->ShowName();
pear->ShowName();
banana->ShowName();
delete factory;
delete apple;
delete pear;
delete banana;
}
/*
单例模式;
1.如何实现单例,实现步骤
(1)构造函数私有化
(2)增加静态私有的当前类的指针变量
(3)提供静态对外接口,可以让用户获得单例对象
单例 分为懒汉式和饿汉式
*/
//single pattern
class A
{
private:
A()
{
a = new A;
}
public:
static A *getInstance()
{
return a;
}
private:
static A* a;
};
A* A::a = NULL;
int main(void)
{
A::getInstance();
}
//分为懒汉式
class Singleton_lazy
{
private:
Singleton_lazy()
{
}
static Singleton_lazy* getInstance()
{
if (pSingleton == NULL)
{
pSingleton = new Singleton_lazy;
}
return pSingleton;
}
private:
static Singleton_lazy* pSingleton;
};
Singleton_lazy* Singleton_lazy::pSingleton = NULL;
//饿汉式
class Singleton_hungry
{
private:
Singleton_hungry()
{
cout << "ehanshi";
}
static Singleton_hungry* getInstance()
{
return pSingleton;
}
#if 0
staic void freeSpace()
{
if (pSingleton != NULL)
{
delete pSingleton;
}
}
#endif
/*
一般单例模式不用考虑对象的释放问题,因为整个程序中只有一份对象,结束后自行销毁;
*/
class Garbo
{
~Garbo()
{
if (pSingleton != NULL)
{
delete pSingleton;
}
}
};
private:
static Singleton_hungry* pSingleton;
static Garbo *garbo;
};
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;
void test01()
{
Singleton_hungry* p1 = Singleton_hungry::getInstance();
Singleton_hungry* p2 = Singleton_hungry::getInstance();
if (p1 == p2)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
Singleton_hungry* p3 = Singleton_lazy::getInstance();
Singleton_hungry* p4 = Singleton_lazy::getInstance();
if (p3 == p4)
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
}
void main(void)
{
//饿汉式先完成对象的初始化
}
/*懒汉式碰到多线程,是线程不安全的;
饿汉式是线程安全的;
代理模式
定义:为其他对象提供一种代理以控制对这个对象的访问;在某些情况下,一个对象
不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
*/
class AbstractCommonInterface
{
public:
virtual void run() = 0;
};
/*
提供一种代理来控制对其他对象的访问
*/
//必须有权限验证,不是所有人都可以来启动我的启动,提供用户名和密码
class MySystem : public AbstractCommonInterface
{
public:
virtual void run()
{
cout << "run system" << endl;
}
};
class MySystemProxy : public AbstractCommonInterface
{
public:
MySystemProxy(string username, string password)
{
this->mPassword = password;
this->mUsername = username;
pSystem = new MySystem;
}
bool checkUsernameAndPassword()
{
if (mUsername == "admin" && mPassword == "admin")
return true;
return false;
}
virtual void run()
{
if (checkUsernameAndPassword())
{
cout << "ok";
this->pSystem->run();
}
else
{
cout << "usernam or password wrong";
}
}
~MySystemProxy()
{
if (pSystem != NULL)
{
delete pSystem;
}
}
public:
MySystem* pSystem;
string mUsername;
string mPassword;
};
void test11()
{
MySystemProxy* proxy = new MySystemProxy("root", "admin");
proxy->run();
}
void main(void)
{
test11();
return 0;
}
/*
根据迪米特法则,如果两个类不必彼此直接通信,那么这两个类就不应该直接的相互作用;
Facade模式也叫外观模式,是由Gof提出的23种设计模式的一种,Facade模式为一组具有类似功能的类群,
比如类库,子系统等等,提供一个一致的简单的界面,这个一致的简单的界面被称为facade.
外观模式就是将复杂的子类系统抽像到一个接口进行管理,
外界只需要通过此接口与子类系统进行交互,而不必要直接与复杂的子类系统进行交互;
*/
class Television
{
public:
void on()
{
cout << "tv open";
}
void off()
{
cout << "tv close";
}
};
class Light
{
public:
void on()
{
cout << "Light open";
}
void off()
{
cout << "Light close";
}
};
class Audio
{
public:
void on()
{
cout << "Audio open";
}
void off()
{
cout << "Audio close";
}
};
class DVDPlayer
{
public:
void on()
{
cout << "DvdPlayer open";
}
void off()
{
cout << "DvdPlayer close";
}
};
class KTVMode
{
public:
KTVMode()
{
pTv = new Television;
pLight = new Light;
pAudio = new Audio;
pMicrophone = new Microphone;
pDvd = new DVDPlayer;
}
~KTVMode()
{
delete pTv;
delete pLight;
delete pAudio;
delete pMicrophone;
delete pDvd;
}
void onKtv()
{
pTv->on();
pLight->off();
pDvd->on();
pMicrophone->on();
pAudio->on();
}
public:
Television *pTv;
Light* pLight;
Audio* pAudio;
MicroPhone* pMicrophone;
DVDPlayer* pDvd;
};
void test00()
{
KTVMode *ktv = new KTVMode;
ktv->onKtv();
}
/*
适配器模式:
1.将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作;
*/
/*
适配器模式:
将已经写好的接口,但是这个接口不符合需求,将写好的接口转换成目标接口
*/
struct Myprint
{
void operator()(int v1, int v2)
{
cout << v1 + v2 << endl;
}
};
//define target interface
class Target
{
public:
virtual void operator()(int v) = 0;
};
//写适配器
class Adapter : public Target
{
public:
Adapter(int param)
{
this->param = param;
}
virtual void operator()(int v)
{
print(v, param);
}
public:
Myprint print;
int param;
};
//MyBind2And
Adapter MyBind2nd(int v)
{
return Adapter(v);
}
int main(void)
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
for_each (v.begin(), v.end(), Adapter(100));
}
/*
行为型模式
1.用来对类或对象怎样交互和怎样分配职责进行描述
模板方法模式;
定义一个操作中算法的框架,而将一些步骤延迟到子类中,模板方法模式使得子类可以不改变一个算法
的结构即可重新定义该算法的某些特定步骤;
*/
/*
1.在父类中形式化地定义一个算法,而由他的子类来实现细节的处理,在子类中
实现详细的处理算法时并不会改变算法的执行步骤;
2.模板方法模式是一种代码复用的技术,它在类库设计中尤为重要,它提取了类库中
公共行为,将公共行为放到父类中,而通过其子类来实现不同的行为,它鼓励我们恰当使用继承来实现代码的复用;
3.可实现一种反向控制结构,通过子类覆盖父类的钩子方法来决定某一特定步骤是否需要执行;
4.在模板方法模式中可以通过子类来覆盖父类的基本方法,不同的子类可以提供基本方法的不同实现,
更换和增加新的子类很方便,符合单一职责原则和开闭原则;
*/
class DrinkTemplate
{
public:
virtual void BoildWater() = 0;
virtual void Brew() = 0;
virtual void PourInCup() = 0;
virtual void AddSomething() = 0;
//template method
void make() {
BoildWater();
Brew();
PourInCup();
AddSomething();
}
};
//子类实现具体的操作
class Coffee : public DrinkTemplate
{
public:
virtual void BoildWater()
{
cout << "fff";
}
virtual void Brew()
{
cout << "fff";
}
virtual void PourInCup()
{
cout << "fff";
}
virtual void AddSomething()
{
cout << "fff";
}
};
class Tea : public DrinkTemplate
{
public:
virtual void BoildWater()
{
cout << "fff";
}
virtual void Brew()
{
cout << "fff";
}
virtual void PourInCup()
{
cout << "fff";
}
virtual void AddSomething()
{
cout << "fff";
}
};
void test()
{
Tea* tea = new Tea;
tea->make();
Coffee* coffee = new Coffee;
coffee->make();
}
/*
策略模式:
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换。
策略模式让算法独立于使用他们的客户而独立变化;
*/
class WeaponStrategy
{
public:
virtual void UseWeapon() = 0;
};
class Knife : public WeaponStrategy
{
public:
virtual void UseWeapon()
{
cout << "knife use" << endl;
}
};
class AK47 : public WeaponStrategy
{
public:
virtual void UseWeapon()
{
cout << "AK47" << endl;
}
};
class character
{
public:
void setWeapson(WeaponStrategy* weapon)
{
this->pWeapon = weapon;
}
void throwWeapson()
{
this->pWeapon->UseWeapon();
}
public:
WeaponStrategy *pWeapon;
};
void test()
{
character* character = new Character;
WeaponStrategy* knife = new Knife;
WeaponStrategy* ak47 = new AK47;
character->setWeapson(knife);
character->throwWeapson();
character->setWeapson(ak47);
character->throwWeapson();
delete ak47;
delete knife;
delete character;
}
/*
命令模式:
将一个请求封装为一个对象,从而让我们可用不同的请求对客户进行参数化;
对请求排队或者记录请求日志,以及支持可撤销的操作。命令模式是一种对象行为型模式,
其别名为动作(action)模式或事务(Transaction)模式。
命令模式可以将请求发送者和请求接收者完全解耦,发送者和接收者之间没有直接的引用关系,
发送请求的对象只需要知道如何发送请求,而不必知道如何完成请求;
*/
//协议处理类
class HandleClientProtocol
{
public:
//处理增加金币
void AddMoney
{
cout << "add money" << endl;
}
//处理增加钻石
void AddDiamond()
{
cout << "add diamond" << endl;
}
//处理玩家装备
void AddEquipment()
{
cout << "add equipement" << endl;
}
void addLevel()
{
cout << "add level" << endl;
}
};
//command interface
class AbstractCommand
{
public:
virtual void handle() = 0;//处理客户端的请求
};
//处理增加金币的请求
class AddMoneyCommand : public AbstractCommand
{
public:
AddMoneyCommand(HandleClientProtocol* protocol)
{
this->pProtocol = protocol;
}
virtual void handle()
{
this->pProtocol->AddMoney();
}
public:
HandleClientProtocol *pProtocol;
};
//处理增加钻石的请求
class AddDiamondCommand : public AbstractCommand
{
public:
AddDiamondCommand(HandleClientProtocol* protocol)
{
this->pProtocol = protocol;
}
virtual void handle()
{
this->pProtocol->AddDiamond();
}
public:
HandleClientProtocol *pProtocol;
};
//其他请求同上操作
//server program
class Server
{
public:
void addRequest(AbstractCommand* command)
{
mCommands.push(command);
}
void startHandle()
{
while (!mCommands.empty())
{
Sleep(2000);
AbstractCommand* command = mCommands.front();
command->handle();
mCommands.pop();
}
}
public:
queue<AbstractCommand*> mCommands;
};
void test()
{
HandleClientProtocol* protocol = new HandleClientProtocol;
AbstractCommand* addMoney = new AddMoneyCommand(protocol);
AbstractCommand* adddiamond = new AddDiamondCommand(protocol);
AbstractCommand* addEquipment = new AddEquipmentCommand(protocol);
AbstractCommand* addLevel = new AddLevelCommand(protocol);
Server* server = new Server;
server->addRequest(addMoney);
server->addRequest(adddiamond);
server->addRequest(addEquipment);
server->addRequest(addLevel);
server->startHandle();
//delete addMoney;
//delete addEquipment;
//delete addLevel;
//delete adddiamond;
//delete server;
}
/*
观察者模式:
观察者模式是用于建立一种对象与对象之间的依赖关系,一个对象发生改变时将
自动通知其他对象,其他对象将相应作出反应。
在观察者模式中,发生改变的对象称为观察目标,而被通知的对象称为观察者,一个观察者目标可以对应多个
*/
//Abstract hero
class AbstractHero
{
public:
virtual void Update() = 0;
};
class HeroA : public AbstractHero
{
public:
HeroA()
{
cout << "heroA hit boss" << endl;
}
virtual void Update()
{
cout << "stop hiting boss";
}
};
class HeroB : public AbstractHero
{
public:
HeroB()
{
cout << "heroB hit boss" << endl;
}
virtual void Update()
{
cout << "stop hiting boss";
}
};
class HeroC : public AbstractHero
{
public:
HeroC()
{
cout << "heroA hit boss" << endl;
}
virtual void Update()
{
cout << "stop hiting boss";
}
};
//抽象观察target
class AbstractBoss
{
virtual void addHero(AbstractHero* hero) = 0;
virtual void deleteHero(AbstractHero* hero) = 0;
virtual void notify() = 0;
};
具体观察target
class BOSSA : public AbstractBoss
{
public:
virtual void addHero(AbstractHero* hero)
{
pHeroList.push_back(hero);
}
virtual void deleteHero(AbstractHero* hero)
{
pHeroList.remove(hero);
}
virtual void notify()
{
for (list<AbstractHero*>::iterator it = pHeroList.begin(); it != pHeroList.end(); \
it++)
{
(*it)->Update();
}
}
public:
list<AbstractHero*> pHeroList;
};
void test()
{
AbstractHero* heroA = new HeroA;
AbstractHero* heroB = new HeroB;
AbstractHero* heroC = new HeroC;
AbstractBoss* bossA = new BOSSA;
bossA->addHero(heroA);
bossB->addHero(heroB);
bossC->addHero(heroC);
bossA->deleteHero(heroC);
cout << "boss died" << endl;
bossA->notify();
}
/*
一般情况下利用继承实现类的功能拓展
装饰者模式:可以动态给一个类增加新功能
*/
//抽象的英雄
class AbstractHero
{
public:
virtual void ShowStatus() = 0;
public:
int mHp;
int mMp;
int mAt;
int mDf;
};
具体英雄
class HeroA : public AbstractHero
{
public:
HeroA()
{
mHp = 0;
mMp = 0;
mAt = 0;
mDf = 0;
}
virtual void ShowStatus()
{
cout << "dd" << mHp;
cout << "dd" << mMp;
cout << "dd" << mAt;
cout << "dd" << mDf;
}
};
class AbstractEquipment : public AbstractHero
{
public:
AbstractEquipment(AbstractHero* hero)
{
this->pHero = hero;
}
virtual void ShowStatus()
{
}
public:
AbstractHero* pHero;
};
class KuangtuEquipment : public AbstractEquipment
{
public:
KuangtuEquipment(AbstractHero* hero) : AbstractEquipment(hero)
{
}
void AddKuangtu()
{
this->mAt = this->pHero->mAt;
this->mHp = this->pHero->mHp;
this->mMp = this->pHero->mMp;
this->mDf = this->pHero->mDf + 30;
delete this->pHero;
}
virtual void ShowStatus()
{
AddKuangtu();
cout << mHp;
cout << mAt;
cout << mMp;
cout << mDf;
}
};
class Wujinzhiren : public AbstractEquipment
{
public:
Wujinzhiren(AbstractHero* hero) : AbstractEquipment(hero)
{
}
void AddKuangtu()
{
this->mAt = this->pHero->mAt + 20;
this->mHp = this->pHero->mHp;
this->mMp = this->pHero->mMp;
this->mDf = this->pHero->mDf;
delete this->pHero;
}
virtual void ShowStatus()
{
AddKuangtu();
cout << mHp;
cout << mAt;
cout << mMp;
cout << mDf;
}
};
void test()
{
AbstractHero *hero = new HeroA;
hero->ShowStatus();
hero = new KuangtuEquipment(hero);
hero->ShowStatus();
hero = new Wujinzhiren(hero);
hero->ShowStatus();
}