#include <iostream.h>
#include <string.h>
//访问者模式
//将对象针对某种对象会发生的状态作出相应的行为
//关键词: 对象 状态 行为
//对象产生状态,状态激起对象的相应反应(可能是行为也可是另外的一种状态)
//即对象对状态的处理需要状态作为参数,而处理需要的结果又是由状态产生
//所以对象又将自己作为参数传递给状态的相应方法去处理
//好处是在对象分类稳定的前提下但状态需要增加的时候,只需要增加状态就行,代码改动很少
class person //抽象对象类 人
{
public:
char *type; //性别
public:
person(){}
virtual ~person(){}
};
class status //抽象状态类
{
protected:
char *sts; //状态
public:
status(){}
virtual ~status(){}
public:
virtual void GetObjRelForSt(person *per) = 0 ; //获取对象在相应状态下的反应
};
class Success : public status
{
public:
Success(){sts = "成功";}
virtual ~Success(){}
public:
virtual void GetObjRelForSt(person *per) //直接作出对象的相应反应即可
{
if(!strcmp("男人",per->type))
cout << per->type << this->sts << "背后寡然" << endl;
else
cout << per->type << this->sts << "背后人众" << endl;
}
};
class Worse : public status
{
public:
Worse(){sts = "失败";}
virtual ~Worse(){}
public:
virtual void GetObjRelForSt(person *per) //直接作出对象的相应反应即可
{
if(!strcmp("男人",per->type))
cout << per->type << this->sts << "沉默寡言" << endl;
else
cout << per->type << this->sts << "哭天哭地" << endl;
}
};
class Man : public person
{
public:
Man(){type = "男人";}
virtual ~Man(){}
public:
void GetPersonStatus(status *status)
{
status->GetObjRelForSt(this);
}
};
class Woman : public person
{
public:
Woman(){type = "女人";}
virtual ~Woman(){}
public:
void GetPersonStatus(status *status)
{
status->GetObjRelForSt(this);
}
};
void main()
{
person *man = new Man();
person *woman = new Woman();
status *success = new Success();
static_cast<Man*>(man)->GetPersonStatus(success);
static_cast<Woman*>(woman)->GetPersonStatus(success);
}