设计模式3—行为型模式


行为型模式用来对类或对象怎样交互和怎样分配职责进行描述,主要包含以下11种设计模式:

  1. 模板方法模式(Template Method Pattern)
    使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
  2. 命令模式(Command Pattern)
    是将一个请求封装为一个对象,从而使你可用不同的请求对客户端进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
  3. 责任链模式(Chain of Responsibility Pattern)
    在该模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求,这使得系统可以在不影响客户端的情况下动态地重新组织链和分配责任。
  4. 策略模式(Strategy Pattern)
    就是准备一组算法,并将每一个算法封装起来,使得它们可以互换。
  5. 中介者模式(Mediator Pattern)
    就是定义一个中介对象来封装系列对象之间的交互。终结者使各个对象不需要显示的相互调用 ,从而使其耦合性松散,而且可以独立的改变他们之间的交互。
  6. 观察者模式(Observer Pattern)
    定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
  7. 备忘录模式(Memento Pattern)
    是在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
  8. 访问者模式(Visitor Pattern)
    就是表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
  9. 状态模式(State Pattern)
    就是对象的行为,依赖于它所处的状态。
  10. 解释器模式(Interpreter Pattern)
    就是描述了如何为简单的语言定义一个语法,如何在该语言中表示一个句子,以及如何解释这些句子。
  11. 迭代器模式(Iterator Pattern)
    是提供了一种方法顺序来访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。


1. 模板方法模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

//
/*
	所谓的模板模式: 
	把业务逻辑给做好(和外观模式类似,只是按一定顺序调用)
	就是按一定次序调用
*/
//
class Car
{
public:
	virtual void makeCarHead() = 0;
	virtual void makeCarBody() = 0;
	virtual void makeCarTail() = 0;
	void makeCar()
	{
		//直接按一定顺序调度函数
		makeCarBody(); //先造车身
		makeCarHead(); //再造车头
		makeCarTail(); //最后造车尾
	}
protected:
private:
};
//
class Jeep : public Car
{
public:
	virtual void makeCarHead()
	{
		cout << "jeep head" << endl;
	}
	virtual void makeCarBody()
	{
		cout << "jeep body" << endl;
	}
	virtual void makeCarTail()
	{
		cout << "jeep tail" << endl;
	}
};

class Bus : public Car
{
public:
	virtual void makeCarHead()
	{
		cout << "Bus head" << endl;
	}
	virtual void makeCarBody()
	{
		cout << "Bus body" << endl;
	}
	virtual void makeCarTail()
	{
		cout << "Bus tail" << endl;
	}
};

int main()
{
	Car *car = new Bus;
	car->makeCar();
	delete car;

	Car *car2 = new Jeep;
	car2->makeCar();
	delete car2;

	system("pause");
	return 0;
}

2. 命令模式

#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <iostream>
using namespace std;


//
/*
Command模式也叫命令模式 ,是行为设计模式的一种。Command模式通过被称为
Command的类封装了对目标对象的调用行为以及调用参数。

在面向对象的程序设计中,一个对象调用另一个对象,
一般情况下的调用过程是:创建目标对象实例;设置调用参数;调用目标对象的方法。
但在有些情况下有必要使用一个专门的类对这种调用过程加以封装,
我们把这种专门的类称作command类。

*/
//


class Doctor
{
public:
	void treat_eye()
	{
		cout << "医生 治疗 眼睛" << endl;
	}
	void treat_nose()
	{
		cout << "医生 治疗 鼻子" << endl;
	}
protected:
private:
};

class CommandTreatEye
{
public:
	CommandTreatEye(Doctor *doctor)
	{
		m_doctor = doctor;
	}
	void treat()
	{
		m_doctor->treat_eye();
	}
private:
	Doctor *m_doctor;
};

class CommandTreatNose
{
public:
	CommandTreatNose(Doctor *doctor)
	{
		m_doctor = doctor;
	}
	void treat()
	{
		m_doctor->treat_nose();
	}
private:
	Doctor *m_doctor;
};

//命令可以在抽象
class Command
{
public:
	virtual void treat() = 0;
protected:
private:
};
class TreatEye : public Command
{
public:
	TreatEye(Doctor* doctor) :m_doctor(doctor){}
	virtual void treat()
	{
		m_doctor->treat_eye();
	}
protected:
private:
	Doctor *m_doctor;
};
class TreatNose :public Command
{
public:
	TreatNose(Doctor* doctor) :m_doctor(doctor){}
	virtual void treat()
	{
		m_doctor->treat_nose();
	}
protected:
private:
	Doctor *m_doctor;
};

class BeautyNurse
{
public:
	BeautyNurse(Command* command):m_command(command){}

	void submitCase()
	{
		m_command->treat();
	}
protected:
private:
	Command *m_command;
};
class HeadNurse
{
public:
	HeadNurse()
	{
		m_list.clear();
	}
public:
	void setCommand(Command *command)
	{
		m_list.push_back(command);
	}
	void SubmittedCase() //提交病例 下单命令
	{
		for (list<Command *>::iterator it = m_list.begin(); it != m_list.end(); it++)
		{
			(*it)->treat();
		}
	}
private:
	list<Command *> m_list;
};

int main()
{
	//1 一般的医生直接看病
	cout << "一般的医生直接看病" << endl;
	Doctor *doctor = new Doctor ;
	doctor->treat_eye();
	delete doctor;
	cout << endl;
	
	//2 通过一个命令 医生通过 命令 治疗 治病
	cout << "通过一个命令 医生通过 命令 治疗 治病" << endl;
	doctor = new Doctor;
	CommandTreatEye * commandtreateye = new CommandTreatEye(doctor); //shift +u //转小写 shift+ctl + u转大写
	commandtreateye->treat();
	delete commandtreateye;
	delete doctor;
	cout << endl;


	//护士提交简历 给以上看病
	BeautyNurse		*beautynurse = NULL;	
	Command			*command = NULL;

	
	cout << "\n护士发送号令" << endl;
	command = new TreatNose(doctor); //shift +u //转小写 shift+ctl + u转大写
	beautynurse = new BeautyNurse(command);
	beautynurse->submitCase();	
	delete command;
	delete beautynurse;


	//通过护士长 批量的下单命令
	//护士提交简历 给以上看病
	cout << "\n护士长发送号令" << endl;
	HeadNurse		*headnurse = NULL;
	Command			*command1 = NULL;
	Command			*command2 = NULL;
	
	command1 = new TreatEye(doctor); //shift +u //转小写 shift+ctl + u转大写
	command2 = new TreatNose(doctor); //shift +u //转小写 shift+ctl + u转大写

	headnurse = new HeadNurse(); //new 护士长
	headnurse->setCommand(command1);
	headnurse->setCommand(command2);

	headnurse->SubmittedCase(); // 护士长 批量下单命令
	
	delete command1;
	delete command2;
	delete headnurse;


	system("pause");
	return 0;
}

3. 责任链模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

//
/*
	Chain of Responsibility(CoR)模式也叫职责链模式或者职责连锁模式,是行为模式之一,
	该模式构造一系列分别担当不同的职责的类的对象来共同完成一个任务,这些类的对象之间
	像链条一样紧密相连,所以被称作职责链模式。

	例1:比如客户Client要完成一个任务,这个任务包括a,b,c,d四个部分。
	首先客户Client把任务交给A,A完成a部分之后,把任务交给B,B完成b部分,...,直到D完成d部分。
	例2:比如政府部分的某项工作,县政府先完成自己能处理的部分,不能处理的部分交给省政府,
	     省政府再完成自己职责范围内的部分,不能处理的部分交给中央政府,中央政府最后完成该项工作。
	例3:软件窗口的消息传播。
	例4:SERVLET容器的过滤器(Filter)框架实现。(就是按顺序一个一个执行(链表))
*/
//

class Car
{
public:
	virtual void makeCar() = 0;
	virtual void improveMakeCar() = 0;
	Car *setNextHandle(Car *car)
	{
		m_car = car;
		return m_car;
	}
protected:
	Car* m_car; //下一个处理单元
private:
};
class MakeCarHead : public Car
{
public:
	virtual void makeCar()
	{
		cout << "造 车头" << endl;
	}
	virtual void improveMakeCar()
	{
		cout << "造 车头" << endl;
		m_car->makeCar();
	}
protected:
private:
	
};
class MakeCarBody : public Car
{
public:
	virtual void makeCar()
	{
		cout << "造 车身" << endl;
	}
	virtual void improveMakeCar()
	{
		cout << "造 车身" << endl;
		m_car->makeCar(); 
	}
protected:
private:
	
};
class MakeCarTail : public Car
{
public:
	virtual void makeCar()
	{
		cout << "造 车尾" << endl;
	}
	virtual void improveMakeCar()
	{
		cout << "造 车尾" << endl;
		m_car->makeCar(); 
	}
protected:
private:
	
};

int main()
{
	cout << "----------问题抛出-------------- " << endl;
	Car *makeCarHead = new MakeCarHead;
	Car *makeCarBody = new MakeCarBody;
	Car *makeCarTail = new MakeCarTail;

	//业务逻辑 写死在客户端了..
	makeCarHead->makeCar();
	makeCarBody->makeCar();
	makeCarTail->makeCar();

	delete makeCarTail;
	delete makeCarBody;
	delete makeCarHead;

	cout << "\n----------改进后(即责任链模式)-------------- " << endl;
	makeCarHead = new MakeCarHead;
	makeCarBody = new MakeCarBody;
	makeCarTail = new MakeCarTail;

	//任务的处理关系
	makeCarBody->setNextHandle(makeCarHead);
	makeCarHead->setNextHandle(makeCarTail);
	makeCarTail->setNextHandle(makeCarBody);
	
	makeCarBody->makeCar();
	makeCarHead->makeCar();
	makeCarTail->makeCar();

	delete makeCarTail;
	delete makeCarBody;
	delete makeCarHead;

	system("pause");
	return 0;
}

4. 策略模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

class Policy
{
public:
	virtual void crypt() = 0;
protected:
private:
};

class AES : public Policy
{
public:
	virtual void crypt()
	{
		cout << "AES加密算法" << endl;
	}
protected:
private:
};

class Context
{
public:
	void setPolicy(Policy* policy)
	{
		this->policy = policy;
		this->policy->crypt();
	}
protected:
private:
	Policy* policy;
};

class DES : public Policy
{
public:
	virtual void crypt()
	{
		cout << "DES 加密算法" << endl;
	}
protected:
private:
};

int main()
{	
	DES *des = new DES;
	des->crypt();
	delete des;

	Policy *policy = NULL;
	
	policy = new AES;
	Context *context = new Context;
	context->setPolicy(policy);
	
	delete  policy;
	delete  context;

	system("pause");
	return 0;
}

5. 中介者模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
//
/*
		适用于:
		用一个中介对象,封装一些列对象(同事)的交换,中介者是各个对象不需要显示的相互作用,
		从而实现了耦合松散,而且可以独立的改变他们之间的交换。
		模式优点
		1,将系统按功能分割成更小的对象,符合类的最小设计原则
		2,对关联对象的集中控制
		3,减小类的耦合程度,明确类之间的相互关系:当类之间的关系过于复杂时,
		   其中任何一个类的修改都会影响到其他类,不符合类的设计的开闭原则 ,
		   而Mediator模式将原来相互依存的多对多的类之间的关系简化为Mediator控制类
		   与其他关联类的一对多的关系,当其中一个类修改时,可以对其他关联类不产生影响
		   (即使有修改,也集中在Mediator控制类)。
		4,有利于提高类的重用性
*/
//

class Person
{
public:
	Person(string name, int sex, int condition)
		:m_name(name), m_sex(sex), m_condition(condition){}

	string getName()
	{
		return m_name;
	}
	int getSex()
	{
		return m_sex;
	}
	int getCondi()
	{
		return m_condition;
	}
	virtual void getParter(Person *p) = 0;
protected:
	string m_name; //名字
	int m_sex;// 性别
	int m_condition; //条件
private:
	
};

class Man : public Person
{
public:
	Man(string name, int sex, int condition)
		:Person(name, sex, condition)
	{}

	virtual void getParter(Person *p)
	{
		if (this->m_sex == p->getSex())
		{
			cout << "我喜欢女人" << endl;
		}
		if (this->getCondi() == p->getCondi())
		{
			cout << this->getName() << " 和 " << p->getName() << "绝配 " << endl;
		}
		else
		{
			cout << this->getName() << " 和 " << p->getName() << "不配 " << endl;
		}
	}

protected:
private:
};

class Woman : public Person
{
public:
	Woman(string name, int sex, int condition)
		:Person(name,sex,condition)
	{}

	virtual void getParter(Person *p)
	{
		if (this->m_sex == p->getSex())
		{
			cout << "我喜欢男人" << endl;
		}
		if (this->getCondi() == p->getCondi())
		{
			cout << this->getName() << " 和 " << p->getName() << "绝配 " << endl;
		}
		else
		{
			cout << this->getName() << " 和 " << p->getName() << "不配 " << endl;
		}
	}

protected:
private:
};

//
/*
	中介者模式
*/
//

class Mediator;  //前向声明
class PersonM
{
public:
	PersonM(string name, int sex, int condi, Mediator *m)
	{
		m_name = name;
		m_sex = sex;
		m_condi = condi;
		mediator = m;
	}
	string getName()
	{
		return m_name;
	}
	int getSex()
	{
		return m_sex;
	}
	int getCondi()
	{
		return m_condi;
	}
	virtual void getParter(PersonM *p) = 0;

protected:
	string	m_name;
	int		m_sex;
	int		m_condi;
	Mediator *mediator;
};

class Mediator
{
public:
	void setMan(PersonM *man)
	{
		pMan = man;
	}
	void setWoman(PersonM *woman)
	{
		pWoman = woman;
	}

public:
	virtual void getParter()
	{

		if (pWoman->getSex() == pMan->getSex())
		{
			cout << "同性相斥 " << endl;
		}
		if (pWoman->getCondi() == pMan->getCondi())
		{
			cout << pWoman->getName() << " 和 " << pMan->getName() << "绝配 " << endl;
		}
		else
		{
			cout << pWoman->getName() << " 和 " << pMan->getName() << "不配 " << endl;
		}
	}
private:
private:
	PersonM	*pMan;
	//list<Person *> m_list;
	PersonM	*pWoman; //
};

class WomanM : public PersonM
{
public:
	WomanM(string name, int sex, int condi, Mediator *m) : PersonM(name, sex, condi, m)
	{

	}
	virtual void getParter(PersonM *p)
	{
		mediator->setMan(p);
		mediator->setWoman(this);
		mediator->getParter(); //找对象 
	}
};

class ManM : public PersonM
{
public:
	ManM(string name, int sex, int condi, Mediator *m) : PersonM(name, sex, condi, m)
	{

	}
	virtual void getParter(PersonM *p)
	{
		mediator->setMan(this);
		mediator->setWoman(p);
		mediator->getParter(); //找对象 
	}
};

int main()
{
	Person *xiaofang = new Woman("小芳", 2, 5);
	Person *zhangsan = new Man("张三", 1, 4);
	Person *lisi = new Man("李四", 1, 5);
	xiaofang->getParter(zhangsan);
	xiaofang->getParter(lisi);

	delete lisi; lisi = NULL;
	delete zhangsan; zhangsan = NULL;
	delete xiaofang; xiaofang = NULL;

	cout << "\n----------------------中介者模式------------------------" << endl;
	Mediator *m = new Mediator;
	PersonM *xiaofangM = new WomanM("小芳", 2, 5, m);

	PersonM *zhangsanM = new ManM("张三", 1, 4, m);

	PersonM *lisiM = new ManM("李四", 1, 5, m);
	xiaofangM->getParter(zhangsanM);

	xiaofangM->getParter(lisiM);

	system("pause");
	return 0;
}

6. 观察者模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <list>
using namespace std;
//
/*
	观察者模式
	(就是相互注入到对方的类中,成为对方的成员。然后通过成员调用对方的成员)

	Observer模式是行为模式之一,它的作用是当一个对象的状态发生变化时,
		能够自动通知其他关联对象,自动刷新对象状态。
	Observer模式提供给关联对象一种同步通信的手段,
		使某个对象与依赖它的其他对象之间保持状态同步。秘书通知观察者
*/
//

class Secretary; //前向声明

class PlayserObserver  //观察者
{
public:
	PlayserObserver(Secretary* secretarty)
	{
		this->m_secretary = secretarty;
	}
	void update(string action)
	{
		cout << "action:" << action << endl;
		cout << "老板来了,注意隐蔽" << endl;
	}
	void update2(string action)
	{
		cout << "action:" << action << endl;
		cout << "老板走了,欢呼吧" << endl;
	}
protected:
private:
	Secretary* m_secretary;
};

class Secretary
{
public:
	Secretary()
	{
		m_list.clear();
	}
	void Notify(string info)
	{
		//给所有的 观察者 发送 情报
		for (list<PlayserObserver *>::iterator it = m_list.begin(); it != m_list.end(); it++)
		{
			(*it)->update(info); //
		}
	}
	void setPlayserObserver(PlayserObserver *o)
	{
		m_list.push_back(o);
	}

protected:
private:
	list<PlayserObserver *> m_list;
};

int main()
{
	Secretary			*secretary = NULL;
	PlayserObserver		*po1 = NULL;
	PlayserObserver		*po2 = NULL;

	secretary = new Secretary;
	po1 = new PlayserObserver(secretary);
	po2 = new PlayserObserver(secretary);

	secretary->setPlayserObserver(po1);
	secretary->setPlayserObserver(po2);

	secretary->Notify("老板come back");
	secretary->Notify("老板has gone");
	delete secretary;
	delete po1;
	delete po2;

	system("pause");
	return 0;
}

7. 备忘录模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

//
/*
	Memento模式也叫备忘录模式,是行为模式之一,
	它的作用是保存对象的内部状态,并在需要的时候(undo/rollback)恢复对象以前的状态。
	(注意当有指针时发生深拷贝、浅拷贝的问题)

	其实就是用“一个类的对象保存另一个类的对象的数据”
*/
//

//Caretaker 管理者
// MememTo  备忘录

class MememTo
{
public:
	MememTo(string name, int age)
	{
		m_name = name;
		m_age = age;
	}
	string getName(){ return m_name; }
	int getAge(){ return m_age; }

	void setName(string name){ this->m_name = name; }
	void setAge(int age){ this->m_age = age; }
protected:
private:
	string	m_name;
	int		m_age;
};

class  Person
{
public:
	Person(string name, int age){ m_name = name; m_age = age; }
	string getName(){ return m_name; }
	int getAge(){ return m_age; }

	void setName(string name){ this->m_name = name; }
	void setAge(int age){ this->m_age = age; }

	//保存
	MememTo* createMememTo(){ return new MememTo(m_name, m_age); }
	//还原 
	void setMememTo(MememTo* memto)
	{
		this->m_age = memto->getAge();
		this->m_name = memto->getName();
	}
public:
	void printT()
	{
		cout << "m_name:" << m_name << " m_age:" << m_age << endl;
	}
private:
	string	m_name;
	int		m_age;
};

class Caretaker
{
public:
	Caretaker(MememTo *memto)
	{
		this->memto = memto;
	}
	MememTo *getMememTo()
	{
		return memto;
	}
	void setMememTo(MememTo *memto)
	{
		this->memto = memto;
	}
protected:
private:
	MememTo *memto;
};

int main()
{
	MememTo *memto = NULL;
	Person *p = new Person("张三", 32);
	p->printT();

	//创建 Person对象的一个状态
	printf("---------\n");
	memto = p->createMememTo(); //保存p的数据成员的值 到 memto 中
	p->setAge(42);
	p->printT();

	printf("还原旧的状态\n");
	p->setMememTo(memto); //从 memto中还原p原来的数据
	p->printT();
	delete memto;
	delete p;

	//MememTo *memto = NULL;
	Caretaker *caretaker = NULL;
	p = new Person("张三", 32);
	p->printT();

	//创建 Person对象的一个状态
	printf("---------\n");
	caretaker = new Caretaker(p->createMememTo());
	p->setAge(42);
	p->printT();

	printf("还原旧的状态\n");
	p->setMememTo(caretaker->getMememTo());
	p->printT();

	delete caretaker;
	delete p;

	system("pause");
	return 0;
}

8. 访问者模式

#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
using namespace std;

//
/*
	Visitor模式也叫访问者模式,是行为模式之一,它分离对象的数据和行为,
	使用Visitor模式,可以不修改已有类的情况下,增加新的操作角色和职责。

	抽象访问者(Visitor)角色:声明了一个或者多个访问操作,形成所有的具体元素角色必须实现的接口。
	具体访问者(ConcreteVisitor)角色:实现抽象访问者角色所声明的接口,也就是抽象访问者所声明的各个访问操作。
	抽象节点(Element)角色:声明一个接受操作,接受一个访问者对象作为一个参量。
	具体节点(ConcreteElement)角色:实现了抽象元素所规定的接受操作。
	结构对象(ObiectStructure)角色:有如下的一些责任,可以遍历结构中的所有元素;
			如果需要,提供一个高层次的接口让访问者对象可以访问每一个元素;
			如果需要,可以设计成一个复合对象或者一个聚集,如列(List)或集合(Set)。

	适用于:
	两批人事物;随意的增加操作。相互解耦合。(多对多的操作)

*/
//


// Visitor  ParkElement
//访问者  访问  公园   (多对多的关系)
//不同类型的访问者<-------->公园中不同的部分(园中园)

class ParkElement;
class Visitor
{
public:
	virtual void visit(ParkElement *parkelement) = 0;
};

class ParkElement
{
public:
	virtual void accept(Visitor *visit) = 0;
};
class  ParkA : public ParkElement   //园中园A
{
public:
	virtual void accept(Visitor *v)
	{
		v->visit(this); //公园接受访问者访问 让访问者做操作
	}
};
class  ParkB : public ParkElement  //园中园B
{
public:
	virtual void accept(Visitor *v)
	{
		v->visit(this); //公园接受访问者访问 让访问者做操作
	}
};
//整个公园 
class Park : public ParkElement    //整个公园
{
public:
	Park()
	{
		m_list.clear();
	}
	void setParkElement(ParkElement *pe)
	{
		m_list.push_back(pe);  //添加公园的各个部分
	}

public:
	virtual void accept(Visitor *v)
	{
		//v->visit(this); //公园接受访问者访问 让访问者做操作

		for (list<ParkElement *>::iterator it = m_list.begin(); it != m_list.end(); it++)
		{
			(*it)->accept(v);  //公园A 公园B 接受 管理者v访问
		}
	}

private:
	list<ParkElement *> m_list; //公园的每一部分  //应该让公园的每一个部分 都让 管理者访问
};

class VisitorA : public Visitor  //访问者A
{
public:
	virtual void visit(ParkElement *parkelement)
	{
		cout << "访问者 A 访问 园中园A " << endl; //parkelement->getName();
	}
};

class VisitorB : public Visitor  //访问者B
{
public:
	virtual void visit(ParkElement *parkelement)
	{
		cout << "访问者 B 访问 园中园B " << endl; //parkelement->getName();
	}
};

class ManagerVisitor : public Visitor
{
public:
	virtual void visit(ParkElement *parkelement)
	{
		cout << "管理者 访问公园 的 各个部分 " << endl; //parkelement->getName();
	}
};

int main()
{

	Visitor *vA = new  VisitorA;
	Visitor *vB = new  VisitorB;

	ParkA *parkA = new ParkA;
	ParkB *parkB = new ParkB;

	//
	parkA->accept(vA);
	parkB->accept(vB);

	delete vA;
	delete vB;
	delete parkA;
	delete parkB;


	cout << "-------------------------------" << endl;
	Visitor *vManager = new  ManagerVisitor;
	Park *park = new Park;

	ParkElement *parkAA = new ParkA;
	ParkElement *parkBB = new ParkB;

	park->setParkElement(parkAA); //添加园中园A
	park->setParkElement(parkBB); //添加园中园B

	//整个公园 接受 管理者访问
	park->accept(vManager); //因为有 A、B公园,所以A、B个输出 一次

	delete parkAA;
	delete parkBB;
	delete park;
	delete vManager;

	system("pause");
	return 0;
}

9. 状态模式

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
//
/* 
				 状态模式
	适用于:对象的行为,依赖于它所处的当前状态。行为随状态改变而改变的场景。
*/
//

class Worker; //前向声明

class State
{
public:
	virtual void doSomeThing(Worker *w) = 0;
};
class State1 : public State
{
public:
	void doSomeThing(Worker *w);
};

class State2 : public State
{
public:
	void doSomeThing(Worker *w);
};


class Worker
{
public:
	Worker()
	{
		m_currstate = new State1;
	}
	int getHour()
	{
		return m_hour;
	}
	void setHour(int hour) //改变状态 7 
	{
		m_hour = hour;
	}
	State* getCurrentState()
	{
		return m_currstate;
	}
	void setCurrentState(State* state) //参数是父类的指针
	{
		m_currstate = state;
	}
	void doSomeThing() //处于不同的状态做不同的 事情
	{
		m_currstate->doSomeThing(this);
	}
private:
	int		m_hour;
	State	*m_currstate; //对象的当前状态
};



void State1::doSomeThing(Worker *w)
{
	if (w->getHour() == 7 || w->getHour() == 8)
	{
		cout << "吃早饭" << endl;
	}
	else
	{
		//-----------------------重点---------------------
		//状态1 不满足时 转向 状态2
		delete w->getCurrentState();  //状态1 不满足 要转到状态2
		w->setCurrentState(new State2);
		w->getCurrentState()->doSomeThing(w); //
	}
}

void State2::doSomeThing(Worker *w)
{
	if (w->getHour() == 9 || w->getHour() == 10)
	{
		cout << "工作" << endl;
	}
	else
	{
		//-----------------------重点---------------------
		//状态1 不满足时 转向 状态2
		delete w->getCurrentState(); //状态2 不满足 要转到状态3 后者恢复到初始化状态
		w->setCurrentState(new State1); //恢复到当初状态
		cout << "当前时间点:" << w->getHour() << "未知状态" << endl;
	}
}

int main()
{
	Worker *w1 = new Worker;
	w1->setHour(7);
	w1->doSomeThing();

	w1->setHour(9);
	w1->doSomeThing();

	delete w1;	

	system("pause");
	return 0;
}

10. 解释器模式

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
//
/*
	Context
	解释器上下文环境类。用来存储解释器的上下文环境,比如需要解释的文法等。 AbstractExpression
	解释器抽象类。
	ConcreteExpression
	解释器具体实现类。
*/
//
// Context 
// Expression 
// PlusExpression   加法
// MinusExpression  减法

class Context
{
public:
	Context(int num){ this->m_num = num;}
	int getNum(){ return m_num;}
	int getRes(){ return m_res;}

	void setNum(int num){ this->m_num = num;}
	void  setRes(int res){ this->m_res = res;}
private:
	int m_num;
	int m_res;
};

class Expression
{
public:
	virtual void  interpreter(Context *context) = 0;
private:
	Context		*m_context;
};

//加法
class PlusExpression : public Expression
{
public:
	PlusExpression()
	{
		this->context = NULL;
	}
	virtual void  interpreter(Context *context)
	{
		int num = context->getNum();
		num++;
		context->setNum(num);
		context->setRes(num);
	}
private:
	Context *context;
};

// 减 法
class MinusExpression : public Expression
{
public:
	MinusExpression()
	{
		this->context = NULL;
	}
	virtual void  interpreter(Context *context)
	{
		int num = context->getNum();
		num--;
		context->setNum(num);
		context->setRes(num);
	}
private:
	Context *context;
};

int main()
{
	Expression		*expression = NULL;
	Context			*context = NULL;
	Expression		*expression2 = NULL;

	context = new Context(10);
	cout << context->getNum() << endl;

	expression = new PlusExpression;
	expression->interpreter(context);

	cout << context->getRes() << endl;

	//
	expression2 = new MinusExpression;
	expression2->interpreter(context);
	cout << context->getRes() << endl;

	system("pause");
	return 0;
}

11. 迭代器模式

#include <iostream>
using namespace std;

// MyIterator  Aggregate ContreteIterator ConcreteAggregate
//	a	 b	c	d
//      ▲

typedef int Object;
#define SIZE 5 

class MyIterator
{
public:
	virtual void First() = 0;
	virtual void Next() = 0;
	virtual bool IsDone() = 0;
	virtual Object CurrentItem() = 0;
};

class Aggregate
{
public:
	virtual MyIterator *CreateIterator() = 0;
	virtual Object getItem(int index) = 0;
	virtual int getSize() = 0;
};

class ContreteIterator : public MyIterator
{
public:
	ContreteIterator(Aggregate *ag)
	{
		_ag = ag;
		_current_index = 0;
	}
	virtual void First()
	{
		_current_index = 0;  //让当前 游标 回到位置0
	}
	virtual void Next()
	{
		if (_current_index < _ag->getSize())
		{
			_current_index++;
		}
	}
	virtual bool IsDone()
	{
		return  (_current_index == _ag->getSize());
	}
	virtual Object CurrentItem()
	{
		return _ag->getItem(_current_index);
	}
protected:
private:
	int			_current_index;
	Aggregate	 *_ag;
};


class ConcreteAggregate : public Aggregate
{
public:
	ConcreteAggregate()
	{
		for (int i = 0; i < SIZE; i++)
		{
			object[i] = i + 100;
		}
	}
	virtual MyIterator *CreateIterator()
	{
		return new ContreteIterator(this); //让迭代器 持有一个 集合的 引用 
	}
	virtual Object getItem(int index)
	{
		return object[index];
	}
	virtual int getSize()
	{
		return SIZE;
	}
private:
	Object object[SIZE];
};

void main()
{
	Aggregate * ag = new ConcreteAggregate;

	MyIterator *it = ag->CreateIterator();

	for (; !(it->IsDone()); it->Next())
	{
		cout << it->CurrentItem() << " ";
	}

	delete it;
	delete ag;

	system("pause");
	return;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值