设计模式及C++实现(三)行为行模式及所有设计模式总结

 

目录

 

板方法模式

功能:

类图:

代码:

策略模式

功能:

类图:

代码:

状态模式

功能:

类图:

代码:

观察者模式

功能:

类图:

代码:

备忘录模式

功能:

类图:

代码:

中介者模式

功能:

类图:

代码:

命令模式

功能:

类图:

代码:

访问者模式

功能:

类图:

代码:

责任链模式

功能:

类图:

代码:

迭代器模式

功能:

类图:

代码:

解释器模式

功能:

类图:

代码:

所有设计模式总结


方法模式

功能:

在面向对象系统的分析与设计过程中经常会遇到这样一种情况:对于某一个业务逻辑 (算法实现)在不同的对象中有不同的细节实现,但是逻辑(算法)的框架(或通用的应用 算法)是相同的。Template 提供了这种情况的一个实现框架。 Template 模式是采用继承的方式实现这一点:将逻辑(算法)框架放在抽象基类中,并 定义好细节的接口,子类中实现细节。

类图:

代码:

#include<iostream>

using namespace std;

class AbstractClass
{
protected:
	virtual void PrimitiveOperation1()=0; //算法1
	virtual void PrimitiveOperation2()=0; //算法2
public:
	void TemplateMethod()
	{
		PrimitiveOperation1();
		PrimitiveOperation2();
	}
};
//算法具体实现的类
class RealClass1:public AbstractClass
{
protected:
	void PrimitiveOperation1()
	{
		cout<<"RealClass1::PrimitiveOperation1"<<endl;
	}
	void PrimitiveOperation2()
	{
		cout<<"RealClass1::PrimitiveOperation2"<<endl;
	}
};
class RealClass2:public AbstractClass
{
protected:
	void PrimitiveOperation1()
	{
		cout<<"RealClass2::PrimitiveOperation1"<<endl;
	}
	void PrimitiveOperation2()
	{
		cout<<"RealClass2::PrimitiveOperation2"<<endl;
	}
};

int main()
{
	AbstractClass* real1 = new RealClass1();
	AbstractClass* real2 = new RealClass2();
	real1->TemplateMethod();
	real2->TemplateMethod();


	return 0;
}

策略模式

功能:

Strategy 模式和 Template 模式要解决的问题是相同(类似)的,都是为了给业务逻辑(算 法)具体实现和抽象接口之间的解耦。Strategy 模式将逻辑(算法)封装到一个类(Context) 里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口 的实现委托给组合对象实现。

类图:

代码:

#include<iostream>

using namespace std;

class Strategy
{
public:
	virtual void algorithm()=0;
	virtual ~Strategy(){}
};
class Real1:public Strategy
{
public:
	void algorithm()
	{
		cout<<"Real1::algorithm"<<endl;
	}
};
class Real2:public Strategy
{
public:
	void algorithm()
	{
		cout<<"Real2::algorithm"<<endl;
	}
};
class Context
{
private:
	Strategy* strategy;
public:
	Context(Strategy* s)
	{
		strategy = s;
	}
	void doAvtion()
	{
		strategy->algorithm();
	}
	~Context()
	{
		if(strategy)
			delete strategy;
		strategy = 0;
	}
};

int main()
{
	Strategy* re2 = new Real2();
	Context* con = new Context(re2);
	con->doAvtion();

	return 0;
}

状态模式

功能:

解决以下两个问题:

1)当状态数目不是很多的时候,Switch/Case 可能可以搞定。但是当状态数目很多的时 候(实际系统中也正是如此),维护一大组的 Switch/Case 语句将是一件异常困难并且容易出 错的事情。

2)状态逻辑和动作实现没有分离。在很多的系统实现中,动作的实现代码直接写在状 态的逻辑当中。这带来的后果就是系统的扩展性和维护得不到保证。

类图:

代码:

//state.h 
#ifndef _STATE_H_ 
#define _STATE_H_ 
class Context; //前置声明
class State 
{ 
public: 
	State(); 
	virtual ~State(); 
	virtual void OperationInterface() = 0; 
	virtual void OperationChangeState(Context*) = 0;
protected: 
	bool ChangeState(Context* con,State*st); 
private: 

}; 
class ConcreteStateA:public State 
{ 
public: 
	ConcreteStateA(); 
	virtual ~ConcreteStateA(); 
	virtual void OperationInterface();
	virtual void OperationChangeState(Context*); 
protected: 
private: 
};
class ConcreteStateB:public State 
{ 
public: 
	ConcreteStateB(); 
	virtual ~ConcreteStateB(); 
	virtual void OperationInterface();
	virtual void OperationChangeState(Context*); 
protected: 
private: 
}; 
#endif //~_STATE_H_

//State.cpp 
#include "State.h" 
#include "Context.h" 
#include <iostream> 
using namespace std; 
State::State() 
{ 
} 
State::~State()
{ 
} 
bool State::ChangeState(Context* con,State* st)
{ 
	con->ChangeState(st); 
	return true; 
} 
void State::OperationChangeState(Context* con) 
{ 
} 
ConcreteStateA::ConcreteStateA() 
{ 
} 
ConcreteStateA::~ConcreteStateA() 
{ 
} 
void ConcreteStateA::OperationInterface() 
{ 
	cout<<"ConcreteStateA::OperationInterface......"<<endl;
}
void ConcreteStateA::OperationChangeState(Context* con) 
{ 
	OperationInterface(); 
	this->ChangeState(con,new ConcreteStateB()); 
} 
ConcreteStateB::ConcreteStateB()
{ 
} 
ConcreteStateB::~ConcreteStateB() 
{ 
} 
void ConcreteStateB::OperationInterface() 
{ 
	cout<<"ConcreteStateB::OperationInterface......"<<endl;
} 
void ConcreteStateB::OperationChangeState(Context* con) 
{ 
	OperationInterface(); 
	this->ChangeState(con,new ConcreteStateA()); 
}

//context.h 
#ifndef _CONTEXT_H_ 
#define _CONTEXT_H_ 
class State; 
class Context 
{ 
public: 
	Context(); 
	Context(State* state); 
	~Context(); 
	void OprationInterface(); 
	void OperationChangState(); 
protected: 
private: 
	friend class State; //表明在 State 类中可以访问 Context 类的 private 字段
	bool ChangeState(State* state); 
private: 
	State* _state; 
}; 
#endif //~_CONTEXT_H_

//context.cpp 
#include "Context.h" 
#include "State.h" 
Context::Context() 
{ 
} 
Context::Context(State* state) 
{ 
	this->_state = state;
} 
Context::~Context() 
{ 
	delete _state; 
} 
void Context::OprationInterface() 
{ 
	_state->OperationInterface();
} 
bool Context::ChangeState(State* state) 
{ 
	this->_state = state;
	return true; 
} 
void Context::OperationChangState() 
{ 
	_state->OperationChangeState(this); 
}

//main.cpp
#include<iostream>
#include"Context.h"
#include"State.h"
using namespace std;


int main()
{
	State* st = new ConcreteStateA(); 
	Context* con = new Context(st); 
	//con->OprationInterface();
	con->OperationChangState();
	//con-> OprationInterface ();
	con->OperationChangState();
	con->OprationInterface();
	if (con != NULL) 
		delete con; 
	if (st != NULL)
		st = NULL; 
	return 0;

}

观察者模式

功能:

Observer 模式要解决的问题为:建立一个 一(Subject)对多(Observer)的依赖关系,并且做到当“一”变化的时候,依赖这个“一” 的多也能够同步改变。最常见的一个例子就是:对同一组数据进行统计分析时候,我们希望 能够提供多种形式的表示(例如以表格进行统计显示、柱状图统计显示、百分比统计显示等)。 这些表示都依赖于同一组数据,我们当然需要当数据改变的时候,所有的统计的显示都能够 同时改变。Observer 模式就是解决了这一个问题。

类图:

代码:

//Subject.h
#pragma once
#include<iostream>
#include<list>
#include<string>

using namespace std;
class Observer;
class Subject
{
private:
	list<Observer*> lst;
public:
	Subject(void);
	virtual ~Subject(void);
	void attach(Observer* ob); //增加观察者
	void detach(Observer* ob);  //移除观察者
	void notify();  //通知所有观察者
	virtual void setSubjectState(string str)=0;
	virtual string getSubjectState()=0;
public:

};

class SubjectOne:public Subject
{
private:
	string subjectState;
public:
	void setSubjectState(string str);
	string getSubjectState();
};


//Subject.cpp
#include "Subject.h"
#include"Observer.h"

Subject::Subject(void)
{
}


Subject::~Subject(void)
{
}
void Subject::attach(Observer* ob) //增加观察者
{
	lst.push_back(ob);
}
void Subject::detach(Observer* ob)  //移除观察者
{
	list<Observer*>::iterator ite = lst.begin();
	while(ite != lst.end())
	{
		if(*ite == ob)
		{
			lst.erase(ite);
			break;
		}
		ite++;
	}
}
void Subject::notify()  //通知所有观察者
{
	list<Observer*>::iterator ite = lst.begin();
	while(ite != lst.end())
	{
		(*ite)->update();
		ite++;
	}
}

void SubjectOne::setSubjectState(string str)
{
	subjectState =str;
}
string SubjectOne::getSubjectState()
{
	return subjectState;
}

//Observer.h
#pragma once
#include"Subject.h"
class Observer
{
public:
	Observer(void);
	~Observer(void);
	virtual void update()=0;
	virtual void printInfo()=0;
};

class RealObserver1:public Observer
{
private:
	string name;
	string observerState;
	Subject* subject;
public:
	RealObserver1(Subject* sub,string name);
	void update();
	void printInfo();
};

class RealObserver2:public Observer //第一类具体观察者。一个观察者对象观察一个。
{
private:
	string name;
	string observerState;
	Subject* subject;
public:
	RealObserver2(Subject* sub,string name);
	void update();
	void printInfo();
};


//Observer.cpp
#include "Observer.h"


Observer::Observer(void)
{
}


Observer::~Observer(void)
{
}

RealObserver1::RealObserver1(Subject* sub,string name)
{
	this->subject = sub;
	this->name = name;
}
void RealObserver1::update()
{
	this->observerState = subject->getSubjectState();
	printInfo();
}
void RealObserver1::printInfo()
{
	cout<<"RealObserver1->"<<this->name<<"->"<<this->observerState<<endl;
}

RealObserver2::RealObserver2(Subject* sub,string name)
{
	this->subject = sub;
	this->name = name;
}
void RealObserver2::update()
{
	this->observerState = subject->getSubjectState();
	printInfo();
}
void RealObserver2::printInfo()
{
	cout<<"RealObserver2->"<<this->name<<"->"<<this->observerState<<endl;
}

//main.cpp
#include"Observer.h"
#include"Subject.h"


int main()
{
	Subject* sub1 = new SubjectOne();  //一
	Observer* ob1 = new RealObserver1(sub1,"one-one"); //多
	Observer* ob2 = new RealObserver2(sub1,"one-two"); //多
	sub1->attach(ob1);
	sub1->attach(ob2);
	sub1->setSubjectState("subject1"); //当一发生变化,他所对应的观察者都跟着一起变化
	sub1->notify();
	sub1->setSubjectState("我变了"); //当一发生变化,他所对应的观察者都跟着一起变化
	sub1->notify();
	return 0;
}

代码说明:

Observer 模式的实现中,Subject 维护一个 list 作为存储其所有观察者的容器。每当 调用Notify操作就遍历list 中的Observer对象,并广播通知改变状态(调用ObserverUpdate 操作)。目标的状态 state 可以由 Subject 自己改变(示例),也可以由 Observer 的某个操作引 起 state 的改变(可调用 Subject SetState 操作)。Notify 操作可以由 Subject 目标主动广播。

备忘录模式

功能:

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以对该对象恢复到原先保存的状态

类图:

代码:

//Originator.h
#pragma once
#include<string>
#include<iostream>
using namespace std;
class Memento;  //备忘录类
class Originator //需要被保护的对象类
{
public:
	Originator(string str);
	~Originator(void);
private:
	string state;
public:
	Memento* createMemento();
	void setMemento(Memento* me);
	void showState();
	void changeState(string str);
};

//Originator.cpp
#include "Originator.h"
#include"Memento.h"

Originator::Originator(string str)
{
	state = str;
}


Originator::~Originator(void)
{
}
Memento* Originator::createMemento()
{
	return new Memento(state);
}
void Originator::setMemento(Memento* me)
{
	state = me->getState();
}
void Originator::showState()
{
	cout<<state<<endl;
}
void Originator::changeState(string str)
{
	state = str;
}

//Memento.h
#pragma once
#include"Originator.h"
class Memento
{
private:
	string state; //存储状态
public:
	Memento(string state);
	~Memento(void);
	string getState();
};


//Memento.cpp
#include "Memento.h"
Memento::Memento(string state)
{
	this->state = state;
}


Memento::~Memento(void)
{
}

string Memento::getState()
{
	return state;
}

//main.cpp
#include"Memento.h"
#include"Originator.h"


int main()
{
	Originator* c = new Originator("on");
	Memento* men = c->createMemento();
	c->showState();
	c->changeState("off");
	c->showState();
	c->setMemento(men);
	c->showState();
	return 0;
}

中介者模式

功能:

当系统规模变大,对象的量变引 起系统复杂度的急剧增加,对象间的通信也变得越来越复杂,这时候我们就要提供一个专门 处理对象间交互和通信的类,这个中介者就是中介者模式。

类图:

代码:

//Mediator.h
#pragma once
#include<string>
using namespace std;
class Colleague;
class Mediator
{
public:
	Mediator(void);
	~Mediator(void);
public:
	Colleague* coll1;
	Colleague* coll2;
public:
	void send(string str,Colleague* coll);
};


//Mediator.cpp
#include "Mediator.h"
#include"Colleague.h"

Mediator::Mediator(void)
{
}


Mediator::~Mediator(void)
{
}

void Mediator::send(string str,Colleague* coll)
{
	if(coll == coll1)
		coll2->getMessage(str);
	else if(coll== coll2)
		coll1->getMessage(str);
}

//Colleague.h
#pragma once
#include<iostream>
#include"Mediator.h"
class Colleague
{
private:
	string message;
	Mediator* me;
public:
	Colleague(Mediator* me);
	~Colleague(void);
	void getMessage(string str);
	void showMessage();
	void send(string str);
};

//Colleague.cpp
#include "Colleague.h"


Colleague::Colleague(Mediator* me)
{
	this->me = me;
}


Colleague::~Colleague(void)
{
}
void Colleague::getMessage(string str)
{
	message = str;
}
void Colleague::showMessage()
{
	cout<<message<<endl;
}
void Colleague::send(string str)
{
	me->send(str,this);
}

//main.cpp
#include"Colleague.h"
#include"Mediator.h"

int main()
{
	Mediator* me = new Mediator();
	Colleague* col1 = new Colleague(me);
	Colleague* col2 = new Colleague(me);
	me->coll1 = col1;
	me->coll2 = col2;
	col1->send("hello coll2");
	col2->showMessage();
	col2->send("hello coll1");
	col1->showMessage();

	return 0;
}

命令模式

功能:

Command 模式通过将请求封装到一个对象(Command)中,并将请求的接受者存放到 具体的 ConcreteCommand 类中(Receiver)中,从而实现调用操作的对象和操作的具体实现 者之间的解耦。

类图:

Command 模式结构图中,将请求的接收者(处理者)放到 Command 的具体子类 ConcreteCommand 中,当请求到来时(Invoker 发出 Invoke 消息激活 Command 对象), ConcreteCommand 将处理请求交给 Receiver 对象进行处理。

代码:

#include<iostream>
using namespace std;

class Receiver
{
public:
	void action()
	{
		cout<<"executing..."<<endl;
	}
};

class Command
{
private:
	Receiver* rec;
public:
	Command(Receiver* rec)
	{
		this->rec = rec;
	}
	void execute()
	{
		rec->action();
	}
};

class Invoker
{
private:
	Command* com;
public:
	void setCommand(Command* com)
	{
		this->com = com;
	}
	void executeCommand()
	{
		com->execute();
	}
};

int main()
{
	Receiver* rec = new Receiver();
	Command* com = new Command(rec);
	Invoker* in = new Invoker();
	in->setCommand(com);
	in->executeCommand();

	return 0;
}

访问者模式

功能:

不改变类的前提下定义作用于这些元素的新操作。

类图:

代码:

//伪代码:
class Visitor
{
public:
    virtual void visitorElementA(ElementA* eleA)=0;
    virtual void visitorElementB(ElementB* eleB)=0;
};
class Visitor1:public Visitor
{
public:
    void visitorElementA(ElementA* eleA)
    {
        cout<<"eleA被 visitor1访问"<<endl;
    }
    void visitorElementB(ElementB* eleB);
    {
        cout<<"eleB被 visitor1访问"<<endl;
    }
};
class Visitor2:public Visitor
{
public:
    void visitorElementA(ElementA* eleA)
    {
        cout<<"eleA被 visitor2访问"<<endl;
    }
    void visitorElementB(ElementB* eleB);
    {
        cout<<"eleB被 visitor2访问"<<endl;
    }
};

class Element
{
public:
    virtual accept(Visitor* vi)=0;
};
class ElementA:public Element
{
public:
    void accept(Visitor* vi)
    {
        vi->visitorElementA(this);
    }
};
class ElementB:public Element
{
public:
    void accept(Visitor* vi)
    {
        vi->visitorElementB(this);
    }
};

int main()
{
    Visitor* vi1 = new Visitor1();
    Element* eleb = new ElementB();
    eleb->accept(vi1); //输出为 eleB被Visitor1访问
}

责任链模式

功能:

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

类图:

代码:

#include<iostream>
#include<string>
using namespace std;

class Manager
{
protected:
	Manager* man;
public:
	virtual void setNext(Manager* m)=0;
	virtual void deal(string str)=0;
};
class Manager1:public Manager
{
private:
	string m_deal;
public:
	Manager1(string str)
	{
		m_deal = str;
	}
	void setNext(Manager* m)
	{
		man = m;
	}
	void deal(string str)
	{
		if(m_deal == str)
			cout<<m_deal<<" dealed it"<<endl;
		else
			man->deal(str);
	}
};



int main()
{

	Manager* man1 = new Manager1("deal1");
	Manager* man2 = new Manager1("deal2");
	Manager* man3 = new Manager1("deal3");
	man1->setNext(man2);
	man2->setNext(man3);
	man1->deal("deal3");


	return 0;
}	

迭代器模式

功能:

提供一种顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表示。

类图:

代码:

//将容器的迭代过程再封装一层,对用户不可见

解释器模式

功能:

翻译解释功能

类图:

代码:

//

所有设计模式总结

创建型模式: https://blog.csdn.net/hhwhg123/article/details/100029648

结构型模式: https://blog.csdn.net/hhwhg123/article/details/100045100

设计模式特点
简单工厂

定义创建对象的接口,封装了对象的创建

工厂方法

在简单工厂的基础上,使得具体化类的工作延迟到了子类中

抽象工厂

提供一个创建一系列或相关依赖对象的接口,而无需指定它们具体的类。

单例生成一个实例
原型

自我复制的功能

建造者将构建过程分步骤进行,使得经过不同步骤创建的对象不同
适配器将一个类的接口转换成希望的接口。
桥接将抽象部分和实现部分抽象化
组合部分-整体。使用户对单个对象和组合对象的使用具有一致性。
装饰者动态的给一个对象添加额外的职责
外观为子系统中的接口提供一致的界面。
享元运用共享技术支持大量细粒度对象
代理为其他对象提供一个代理以控制对这个对象的访问
观察者对象一对多时,当一改变时多改变。
模板方法d定义一个算法骨架,子类实现这个算法
命令将请求封装为一个类。
状态一个对象内部状态改变时改变它的行为,让对象看起来似乎改变了他的类
职责链使多个对象都有机会处理请求,并沿着这些对象形成的链传递请求,直到有对象处理它为止
中介者使对象之间隐式的相互调用,中介者可以帮你进行交互。
解释器翻译解释
访问者给类增加新的功能
策略将一系列算法封装起来,是他们有共同的父类,这样可以相互替换
备忘录捕获一个对象的内部状态,使对象在以后可以恢复
迭代器提供一种方法顺序访问聚合在该类中的元素而不暴露给用户

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值