设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。(引用自百科)
设计模式按类型可分为:创建型、行为型、结构型。
创建型包括:单例模式、抽象工厂模式、工厂方法模式、建造者模式、原型模式。
1、单例模式(Singleton):保证一个类只有一个实例,并提供一个访问它的全局访问点。
1)模式结构:
2)模式时序图:
3)模式代码分析:
#include <iostream>
#include "Singleton.h"
using namespace std;
int main(int argc, char *argv[])
{
Singleton * sg = Singleton::getInstance();
sg->singletonOperation();
return 0;
}
///
// Singleton.cpp
// Implementation of the Class Singleton
///
#include "Singleton.h"
#include <iostream>
using namespace std;
Singleton * Singleton::instance = NULL;
Singleton::Singleton(){
}
Singleton::~Singleton(){
delete instance;
}
Singleton* Singleton::getInstance(){
if (instance == NULL)
{
instance = new Singleton();
}
return instance;
}
void Singleton::singletonOperation(){
cout << "singletonOperation" << endl;
}
运行结果:
2、抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖的对象的接口,而无需指定它们的具体类。
1)模式结构
抽象工厂模式包含如下角色:AbstractFactory:抽象工厂、ConcreteFactory:具体工厂、AbstractProduct:抽象产品、Product:具体产品
2)时序图
3)代码分析
#include <iostream>
#include "AbstractFactory.h"
#include "AbstractProductA.h"
#include "AbstractProductB.h"
#include "ConcreteFactory1.h"
#include "ConcreteFactory2.h"
using namespace std;
int main(int argc, char *argv[])
{
AbstractFactory * fc = new ConcreteFactory1();
AbstractProductA * pa = fc->createProductA();
AbstractProductB * pb = fc->createProductB();
pa->use();
pb->eat();
AbstractFactory * fc2 = new ConcreteFactory2();
AbstractProductA * pa2 = fc2->createProductA();
AbstractProductB * pb2 = fc2->createProductB();
pa2->use();
pb2->eat();
}
///
// ConcreteFactory1.cpp
// Implementation of the Class ConcreteFactory1
///
#include "ConcreteFactory1.h"
#include "ProductA1.h"
#include "ProductB1.h"
AbstractProductA * ConcreteFactory1::createProductA(){
return new ProductA1();
}
AbstractProductB * ConcreteFactory1::createProductB(){
return new ProductB1();
}
///
// ProductA1.cpp
// Implementation of the Class ProductA1
///
#include "ProductA1.h"
#include <iostream>
using namespace std;
void ProductA1::use(){
cout << "use Product A1" << endl;
}
运行结果:
3、工厂方法模式(Factory Method):定义一个用于创建对象的接口,让子类决定实例化哪一个类,使一个类的实例化延迟到了子类中进行。
1)模式结构
工厂方法模式包含如下角色:Product:抽象产品、ConcreteProduct:具体产品、Factory:抽象工厂、ConcreteFactory:具体工厂
2)时序图
3)代码分析
///
// ConcreteFactory.cpp
// Implementation of the Class ConcreteFactory
///
#include "ConcreteFactory.h"
#include "ConcreteProduct.h"
Product* ConcreteFactory::factoryMethod(){
return new ConcreteProduct();
}
#include "Factory.h"
#include "ConcreteFactory.h"
#include "Product.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
Factory * fc = new ConcreteFactory();
Product * prod = fc->factoryMethod();
prod->use();
delete fc;
delete prod;
return 0;
}
4、建造者模式(Builder):将一个复杂对象的构建与它的表示相分离,使得同样的构建过程可以创建不同的表示。
1)模式结构
建造者模式包含如下角色:Builder:抽象建造者、ConcreteBuilder:具体建造者、Director:指挥者、Product:产品角色
2)时序图
3)代码分析
#include <iostream>
#include "ConcreteBuilder.h"
#include "Director.h"
#include "Builder.h"
#include "Product.h"
using namespace std;
int main(int argc, char *argv[])
{
ConcreteBuilder * builder = new ConcreteBuilder();
Director director;
director.setBuilder(builder);
Product * pd = director.constuct();
pd->show();
delete builder;
delete pd;
return 0;
}
///
// ConcreteBuilder.cpp
// Implementation of the Class ConcreteBuilder
///
#include "ConcreteBuilder.h"
ConcreteBuilder::ConcreteBuilder(){
}
ConcreteBuilder::~ConcreteBuilder(){
}
void ConcreteBuilder::buildPartA(){
m_prod->setA("A Style "); //不同的建造者,可以实现不同产品的建造
}
void ConcreteBuilder::buildPartB(){
m_prod->setB("B Style ");
}
void ConcreteBuilder::buildPartC(){
m_prod->setC("C style ");
}
///
// Director.cpp
// Implementation of the Class Director
///
#include "Director.h"
Director::Director(){
}
Director::~Director(){
}
Product* Director::constuct(){
m_pbuilder->buildPartA();
m_pbuilder->buildPartB();
m_pbuilder->buildPartC();
return m_pbuilder->getResult();
}
void Director::setBuilder(Builder* buider){
m_pbuilder = buider;
}
运行结果
5、原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新的对象。
行为型包括:迭代器模式、观察者模式、模版方法模式、命令模式、状态模式、策略模式、责任链模式、中介者模式、访问者模式、解释器模式、备忘录模式 。
6、迭代器模式(Iterator):提供一个方法顺序访问一个聚合对象的各个元素,而又不需要暴露该对象的内部表示。
7、观察者模式(Observer):定义对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
1)模式结构:
观察者模式包含如下角色:Subject: 目标、ConcreteSubject: 具体目标、Observer: 观察者、ConcreteObserver: 具体观察者
2)时序图:
3)代码分析:
#include <iostream>
#include "Subject.h"
#include "Obeserver.h"
#include "ConcreteObeserver.h"
#include "ConcreteSubject.h"
using namespace std;
int main(int argc, char *argv[])
{
Subject * subject = new ConcreteSubject();
Obeserver * objA = new ConcreteObeserver("A");
Obeserver * objB = new ConcreteObeserver("B");
subject->attach(objA);
subject->attach(objB);
subject->setState(1);
subject->notify();
cout << "--------------------" << endl;
subject->detach(objB);
subject->setState(2);
subject->notify();
delete subject;
delete objA;
delete objB;
return 0;
}
///
// Subject.h
// Implementation of the Class Subject
///
#if !defined(EA_61998456_1B61_49f4_B3EA_9D28EEBC9649__INCLUDED_)
#define EA_61998456_1B61_49f4_B3EA_9D28EEBC9649__INCLUDED_
#include "Obeserver.h"
#include <vector>
using namespace std;
class Subject
{
public:
Subject();
virtual ~Subject();
Obeserver *m_Obeserver;
void attach(Obeserver * pObeserver);
void detach(Obeserver * pObeserver);
void notify();
virtual int getState() = 0;
virtual void setState(int i)= 0;
private:
vector<Obeserver*> m_vtObj;
};
#endif // !defined(EA_61998456_1B61_49f4_B3EA_9D28EEBC9649__INCLUDED_)
///
// Subject.cpp
// Implementation of the Class Subject
///
#include "Subject.h"
Subject::Subject(){
}
Subject::~Subject(){
}
void Subject::attach(Obeserver * pObeserver){
m_vtObj.push_back(pObeserver);
}
void Subject::detach(Obeserver * pObeserver){
for(vector<Obeserver*>::iterator itr = m_vtObj.begin();
itr != m_vtObj.end(); itr++)
{
if(*itr == pObeserver)
{
m_vtObj.erase(itr);
return;
}
}
}
void Subject::notify(){
for(vector<Obeserver*>::iterator itr = m_vtObj.begin();
itr != m_vtObj.end();
itr++)
{
(*itr)->update(this);
}
}
///
// Obeserver.h
// Implementation of the Class Obeserver
///
#if !defined(EA_2C7362B2_0B22_4168_8690_F9C7B76C343F__INCLUDED_)
#define EA_2C7362B2_0B22_4168_8690_F9C7B76C343F__INCLUDED_
class Subject;
class Obeserver
{
public:
Obeserver();
virtual ~Obeserver();
virtual void update(Subject * sub) = 0;
};
#endif // !defined(EA_2C7362B2_0B22_4168_8690_F9C7B76C343F__INCLUDED_)
///
// ConcreteObeserver.h
// Implementation of the Class ConcreteObeserver
///
#if !defined(EA_7B020534_BFEA_4c9e_8E4C_34DCE001E9B1__INCLUDED_)
#define EA_7B020534_BFEA_4c9e_8E4C_34DCE001E9B1__INCLUDED_
#include "Obeserver.h"
#include <string>
using namespace std;
class ConcreteObeserver : public Obeserver
{
public:
ConcreteObeserver(string name);
virtual ~ConcreteObeserver();
virtual void update(Subject * sub);
private:
string m_objName;
int m_obeserverState;
};
#endif // !defined(EA_7B020534_BFEA_4c9e_8E4C_34DCE001E9B1__INCLUDED_)
///
// ConcreteObeserver.cpp
// Implementation of the Class ConcreteObeserver
///
#include "ConcreteObeserver.h"
#include <iostream>
#include <vector>
#include "Subject.h"
using namespace std;
ConcreteObeserver::ConcreteObeserver(string name){
m_objName = name;
}
ConcreteObeserver::~ConcreteObeserver(){
}
void ConcreteObeserver::update(Subject * sub){
m_obeserverState = sub->getState();
cout << "update oberserver[" << m_objName << "] state:" << m_obeserverState << endl;
}
运行结果:
8、模版方法模式(Template Method):定义一个操作中的算法骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义某些步骤。
9、命令模式(Command):将一个请求封装为一个对象,从而可以使用不同的请求对客户进行参数化,对请求排队和记录请求日志,以及支持可撤消的操作。
1)模式结构:
命令模式包含如下角色:Command: 抽象命令类、ConcreteCommand: 具体命令类、Invoker: 调用者、Receiver: 接收者、Client:客户类
2)时序图:
3)代码分析:
#include <iostream>
#include "ConcreteCommand.h"
#include "Invoker.h"
#include "Receiver.h"
using namespace std;
int main(int argc, char *argv[])
{
Receiver * pReceiver = new Receiver();
ConcreteCommand * pCommand = new ConcreteCommand(pReceiver);
Invoker * pInvoker = new Invoker(pCommand);
pInvoker->call();
delete pReceiver;
delete pCommand;
delete pInvoker;
return 0;
}
///
// Receiver.h
// Implementation of the Class Receiver
///
#if !defined(EA_8E5430BB_0904_4a7d_9A3B_7169586237C8__INCLUDED_)
#define EA_8E5430BB_0904_4a7d_9A3B_7169586237C8__INCLUDED_
class Receiver
{
public:
Receiver();
virtual ~Receiver();
void action();
};
#endif // !defined(EA_8E5430BB_0904_4a7d_9A3B_7169586237C8__INCLUDED_)
///
// Receiver.cpp
// Implementation of the Class Receiver
///
#include "Receiver.h"
#include <iostream>
using namespace std;
Receiver::Receiver(){
}
Receiver::~Receiver(){
}
void Receiver::action(){
cout << "receiver action." << endl;
}
///
// ConcreteCommand.h
// Implementation of the Class ConcreteCommand
///
#if !defined(EA_1AE70D53_4868_4e81_A1B8_1088DA355C23__INCLUDED_)
#define EA_1AE70D53_4868_4e81_A1B8_1088DA355C23__INCLUDED_
#include "Command.h"
#include "Receiver.h"
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver * pReceiver);
virtual ~ConcreteCommand();
virtual void execute();
private:
Receiver *m_pReceiver;
};
#endif // !defined(EA_1AE70D53_4868_4e81_A1B8_1088DA355C23__INCLUDED_)
///
// ConcreteCommand.cpp
// Implementation of the Class ConcreteCommand
///
#include "ConcreteCommand.h"
#include <iostream>
using namespace std;
ConcreteCommand::ConcreteCommand(Receiver *pReceiver){
m_pReceiver = pReceiver;
}
ConcreteCommand::~ConcreteCommand(){
}
void ConcreteCommand::execute(){
cout << "ConcreteCommand::execute" << endl;
m_pReceiver->action();
}
///
// Invoker.h
// Implementation of the Class Invoker
///
#if !defined(EA_3DACB62A_0813_4d11_8A82_10BF1FB00D9A__INCLUDED_)
#define EA_3DACB62A_0813_4d11_8A82_10BF1FB00D9A__INCLUDED_
#include "Command.h"
class Invoker
{
public:
Invoker(Command * pCommand);
virtual ~Invoker();
void call();
private:
Command *m_pCommand;
};
#endif // !defined(EA_3DACB62A_0813_4d11_8A82_10BF1FB00D9A__INCLUDED_)
///
// Invoker.cpp
// Implementation of the Class Invoker
///
#include "Invoker.h"
#include <iostream>
using namespace std;
Invoker::Invoker(Command * pCommand){
m_pCommand = pCommand;
}
Invoker::~Invoker(){
}
void Invoker::call(){
cout << "invoker calling" << endl;
m_pCommand->execute();
}
运行结果:
10、状态模式(State):允许对象在其内部状态改变时,改变它的行为,对象看起来像改变了它的类。
1)模式结构:
状态模式包含如下角色:Context: 环境类、State: 抽象状态类、ConcreteState: 具体状态类
2)时序图:
3)代码分析:
#include <iostream>
#include "Context.h"
#include "ConcreteStateA.h"
#include "ConcreteStateB.h"
using namespace std;
int main(int argc, char *argv[])
{
char a = '0';
if('0' == a)
cout << "yes" << endl;
else
cout << "no" << endl;
Context * c = new Context();
c->request();
c->request();
c->request();
delete c;
return 0;
}
///
// Context.h
// Implementation of the Class Context
///
#if !defined(EA_F245CF81_2A68_4461_B039_2B901BD5A126__INCLUDED_)
#define EA_F245CF81_2A68_4461_B039_2B901BD5A126__INCLUDED_
#include "State.h"
class Context
{
public:
Context();
virtual ~Context();
void changeState(State * st);
void request();
private:
State *m_pState;
};
#endif // !defined(EA_F245CF81_2A68_4461_B039_2B901BD5A126__INCLUDED_)
///
// Context.cpp
// Implementation of the Class Context
///
#include "Context.h"
#include "ConcreteStateA.h"
Context::Context(){
//default is a
m_pState = ConcreteStateA::Instance();
}
Context::~Context(){
}
void Context::changeState(State * st){
m_pState = st;
}
void Context::request(){
m_pState->handle(this);
}
///
// ConcreteStateA.h
// Implementation of the Class ConcreteStateA
///
#if !defined(EA_84158F08_E96A_4bdb_89A1_4BE2E633C3EE__INCLUDED_)
#define EA_84158F08_E96A_4bdb_89A1_4BE2E633C3EE__INCLUDED_
#include "State.h"
class ConcreteStateA : public State
{
public:
virtual ~ConcreteStateA();
static State * Instance();
virtual void handle(Context * c);
private:
ConcreteStateA();
static State * m_pState;
};
#endif // !defined(EA_84158F08_E96A_4bdb_89A1_4BE2E633C3EE__INCLUDED_)
///
// ConcreteStateA.cpp
// Implementation of the Class ConcreteStateA
///
#include "ConcreteStateA.h"
#include "ConcreteStateB.h"
#include "Context.h"
#include <iostream>
using namespace std;
State * ConcreteStateA::m_pState = NULL;
ConcreteStateA::ConcreteStateA(){
}
ConcreteStateA::~ConcreteStateA(){
}
State * ConcreteStateA::Instance()
{
if ( NULL == m_pState)
{
m_pState = new ConcreteStateA();
}
return m_pState;
}
void ConcreteStateA::handle(Context * c){
cout << "doing something in State A.\n done,change state to B" << endl;
c->changeState(ConcreteStateB::Instance());
}
运行结果:
11、策略模式(Strategy):定义一系列的算法,把它们一个个封装起来,并使它们可以相互替换,使得算法可以独立于它们的用户。
1)模式结构:
策略模式包含如下角色:Context: 环境类、Strategy: 抽象策略类、ConcreteStrategy: 具体策略类
2)时序图:
3)代码分析:
#include <iostream>
#include "Context.h"
#include "ConcreteStrategyA.h"
#include "ConcreteStrategyB.h"
#include "Strategy.h"
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
Strategy * s1 = new ConcreteStrategyA();
Context * cxt = new Context();
cxt->setStrategy(s1);
cxt->algorithm();
Strategy *s2 = new ConcreteStrategyB();
cxt->setStrategy(s2);
cxt->algorithm();
delete s1;
delete s2;
int rac1 = 0x1;
int rac2 = 0x2;
int rac3 = 0x4;
int rac4 = 0x8;
int i = 0xe;
int j = 0x5;
int r1 = i & rac1;
int r2 = i & rac2;
int r3 = i & rac3;
int r4 = i & rac4;
cout <<"res:" << r1 << "/" << r2 << "/" << r3 << "/" << r4 << endl;
return 0;
}
///
// Context.h
// Implementation of the Class Context
///
#if !defined(EA_0DA87730_4DEE_4392_9BAF_4AC64A8A07A4__INCLUDED_)
#define EA_0DA87730_4DEE_4392_9BAF_4AC64A8A07A4__INCLUDED_
#include "Strategy.h"
class Context
{
public:
Context();
virtual ~Context();
void algorithm();
void setStrategy(Strategy* st);
private:
Strategy *m_pStrategy;
};
#endif // !defined(EA_0DA87730_4DEE_4392_9BAF_4AC64A8A07A4__INCLUDED_)
///
// Context.cpp
// Implementation of the Class Context
///
#include "Context.h"
Context::Context(){
}
Context::~Context(){
}
void Context::algorithm(){
m_pStrategy->algorithm();
}
void Context::setStrategy(Strategy* st){
m_pStrategy = st;
}
///
// ConcreteStrategyA.h
// Implementation of the Class ConcreteStrategyA
///
#if !defined(EA_9B180F12_677B_4e9b_A243_1F5DAD93FE1D__INCLUDED_)
#define EA_9B180F12_677B_4e9b_A243_1F5DAD93FE1D__INCLUDED_
#include "Strategy.h"
class ConcreteStrategyA : public Strategy
{
public:
ConcreteStrategyA();
virtual ~ConcreteStrategyA();
virtual void algorithm();
};
#endif // !defined(EA_9B180F12_677B_4e9b_A243_1F5DAD93FE1D__INCLUDED_)
///
// ConcreteStrategyA.cpp
// Implementation of the Class ConcreteStrategyA
///
#include "ConcreteStrategyA.h"
#include <iostream>
using namespace std;
ConcreteStrategyA::ConcreteStrategyA(){
}
ConcreteStrategyA::~ConcreteStrategyA(){
}
void ConcreteStrategyA::algorithm(){
cout << "use algorithm A" << endl;
}
运行结果:
12、责任链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的送发者和接收者之间的耦合关系。
13、中介者模式(Mediator):用一个中介对象封装一些类的对象交互。
1)模式结构:
中介者模式包含如下角色:Mediator: 抽象中介者、ConcreteMediator: 具体中介者、Colleague: 抽象同事类、ConcreteColleague: 具体同事类
2)时序图:
3)代码分析:
#include <iostream>
#include "ConcreteColleagueA.h"
#include "ConcreteMediator.h"
#include "ConcreteColleagueB.h"
using namespace std;
int main(int argc, char *argv[])
{
ConcreteColleagueA * pa = new ConcreteColleagueA();
ConcreteColleagueB * pb = new ConcreteColleagueB();
ConcreteMediator * pm = new ConcreteMediator();
pm->registered(1,pa);
pm->registered(2,pb);
// sendmsg from a to b
pa->sendmsg(2,"hello,i am a");
// sendmsg from b to a
pb->sendmsg(1,"hello,i am b");
delete pa,pb,pm;
return 0;
}
///
// ConcreteMediator.h
// Implementation of the Class ConcreteMediator
///
#if !defined(EA_8CECE546_61DD_456f_A3E7_D98BC078D8E8__INCLUDED_)
#define EA_8CECE546_61DD_456f_A3E7_D98BC078D8E8__INCLUDED_
#include "ConcreteColleagueB.h"
#include "Mediator.h"
#include "ConcreteColleagueA.h"
#include <map>
using namespace std;
class ConcreteMediator : public Mediator
{
public:
ConcreteMediator();
virtual ~ConcreteMediator();
virtual void operation(int nWho,string str);
virtual void registered(int nWho, Colleague * aColleague);
private:
map<int,Colleague*> m_mpColleague;
};
#endif // !defined(EA_8CECE546_61DD_456f_A3E7_D98BC078D8E8__INCLUDED_)
///
// ConcreteMediator.cpp
// Implementation of the Class ConcreteMediator
///
#include "ConcreteMediator.h"
#include <map>
#include <iostream>
using namespace std;
ConcreteMediator::ConcreteMediator(){
}
ConcreteMediator::~ConcreteMediator(){
}
void ConcreteMediator::operation(int nWho,string str){
map<int,Colleague*>::const_iterator itr = m_mpColleague.find(nWho);
if(itr == m_mpColleague.end())
{
cout << "not found this colleague!" << endl;
return;
}
Colleague* pc = itr->second;
pc->receivemsg(str);
}
void ConcreteMediator::registered(int nWho,Colleague * aColleague){
map<int,Colleague*>::const_iterator itr = m_mpColleague.find(nWho);
if(itr == m_mpColleague.end())
{
m_mpColleague.insert(make_pair(nWho,aColleague));
//同时将中介类暴露给colleague
aColleague->setMediator(this);
}
}
///
// ConcreteColleagueA.h
// Implementation of the Class ConcreteColleagueA
///
#if !defined(EA_79979DD4_1E73_46db_A635_E3F516ACCE0A__INCLUDED_)
#define EA_79979DD4_1E73_46db_A635_E3F516ACCE0A__INCLUDED_
#include "Colleague.h"
class ConcreteColleagueA : public Colleague
{
public:
ConcreteColleagueA();
virtual ~ConcreteColleagueA();
virtual void sendmsg(int toWho,string str);
virtual void receivemsg(string str);
};
#endif // !defined(EA_79979DD4_1E73_46db_A635_E3F516ACCE0A__INCLUDED_)
///
// ConcreteColleagueA.cpp
// Implementation of the Class ConcreteColleagueA
///
#include "ConcreteColleagueA.h"
#include <iostream>
using namespace std;
ConcreteColleagueA::ConcreteColleagueA(){
}
ConcreteColleagueA::~ConcreteColleagueA(){
}
void ConcreteColleagueA::sendmsg(int toWho,string str){
cout << "send msg from colleagueA,to:" << toWho << endl;
m_pMediator->operation(toWho,str);
}
void ConcreteColleagueA::receivemsg(string str){
cout << "ConcreteColleagueA reveivemsg:" << str <<endl;
}
运行结果:
14、访问者模式(Visitor):表示一个作用于某对象结构中的各元素的操作,使得可以在不改变各元素类的前提下,定义作用于这个元素的新操作。
15、解释器模式(Interpreter):给定一个语言,定义它的文法的一个表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
16、备忘录模式(Memento):在不破坏对象的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
结构型包括:组合模式、外观模式、代理模式、适配器模式、装饰模式、桥接模式、享元模式。
17、组合模式(Composite):将对象组合成树形结构以表示部分与整体的关系,使得用户对单个对象和组合对象的使用具有一致性。
18、外观模式(Facade):为子系统中的一组接口提供一致的界面,提供一高层接口,这个接口使得子系统更容易使用。
1)模式结构:
外观模式包含如下角色:Facade: 外观角色、SubSystem:子系统角色
2)时序图:
3)代码分析:
#include <iostream>
#include "Facade.h"
using namespace std;
int main(int argc, char *argv[])
{
Facade fa;
fa.wrapOpration();
return 0;
}
///
// Facade.h
// Implementation of the Class Facade
///
#if !defined(EA_FD130A87_92A9_4168_9B33_7A925C47AFD5__INCLUDED_)
#define EA_FD130A87_92A9_4168_9B33_7A925C47AFD5__INCLUDED_
#include "SystemC.h"
#include "SystemA.h"
#include "SystemB.h"
class Facade
{
public:
Facade();
virtual ~Facade();
void wrapOpration();
private:
SystemC *m_SystemC;
SystemA *m_SystemA;
SystemB *m_SystemB;
};
#endif // !defined(EA_FD130A87_92A9_4168_9B33_7A925C47AFD5__INCLUDED_)
///
// Facade.cpp
// Implementation of the Class Facade
// Created on: 06-十月-2014 19:10:44
// Original author: colin
///
#include "Facade.h"
Facade::Facade(){
m_SystemA = new SystemA();
m_SystemB = new SystemB();
m_SystemC = new SystemC();
}
Facade::~Facade(){
delete m_SystemA;
delete m_SystemB;
delete m_SystemC;
}
void Facade::wrapOpration(){
m_SystemA->operationA();
m_SystemB->operationB();
m_SystemC->opeartionC();
}
运行结果:
19、代理模式(Proxy):为其他对象提供一种代理,以控制这个对象的访问。
1)模式结构:
代理模式包含如下角色:Subject: 抽象主题角色、Proxy: 代理主题角色、RealSubject: 真实主题角色
2)时序图:
3)代码分析:
#include <iostream>
#include "RealSubject.h"
#include "Proxy.h"
using namespace std;
int main(int argc, char *argv[])
{
Proxy proxy;
proxy.request();
return 0;
}
///
// Proxy.h
// Implementation of the Class Proxy
///
#if !defined(EA_56011290_0413_40c6_9132_63EE89B023FD__INCLUDED_)
#define EA_56011290_0413_40c6_9132_63EE89B023FD__INCLUDED_
#include "RealSubject.h"
#include "Subject.h"
class Proxy : public Subject
{
public:
Proxy();
virtual ~Proxy();
void request();
private:
void afterRequest();
void preRequest();
RealSubject *m_pRealSubject;
};
#endif // !defined(EA_56011290_0413_40c6_9132_63EE89B023FD__INCLUDED_)
///
// Proxy.cpp
// Implementation of the Class Proxy
///
#include "Proxy.h"
#include <iostream>
using namespace std;
Proxy::Proxy(){
//有人觉得 RealSubject对象的创建应该是在main中实现;我认为RealSubject应该
//对用户是透明的,用户所面对的接口都是通过代理的;这样才是真正的代理;
m_pRealSubject = new RealSubject();
}
Proxy::~Proxy(){
delete m_pRealSubject;
}
void Proxy::afterRequest(){
cout << "Proxy::afterRequest" << endl;
}
void Proxy::preRequest(){
cout << "Proxy::preRequest" << endl;
}
void Proxy::request(){
preRequest();
m_pRealSubject->request();
afterRequest();
}
运行结果:
20、适配器模式(Adapter):将一类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
1)模式结构:
适配器模式包含如下角色:Target:目标抽象类、Adapter:适配器类、Adaptee:适配者类、Client:客户类
适配器模式有对象适配器和类适配器两种实现:
对象适配器:
类适配器:
2)时序图:
3)代码分析:
#include <iostream>
#include "Adapter.h"
#include "Adaptee.h"
#include "Target.h"
using namespace std;
int main(int argc, char *argv[])
{
Adaptee * adaptee = new Adaptee();
Target * tar = new Adapter(adaptee);
tar->request();
return 0;
}
///
// Adapter.h
// Implementation of the Class Adapter
///
#if !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)
#define EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_
#include "Target.h"
#include "Adaptee.h"
class Adapter : public Target
{
public:
Adapter(Adaptee *adaptee);
virtual ~Adapter();
virtual void request();
private:
Adaptee* m_pAdaptee;
};
#endif // !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)
///
// Adapter.cpp
// Implementation of the Class Adapter
///
#include "Adapter.h"
Adapter::Adapter(Adaptee * adaptee){
m_pAdaptee = adaptee;
}
Adapter::~Adapter(){
}
void Adapter::request(){
m_pAdaptee->specificRequest();
}
///
// Adaptee.h
// Implementation of the Class Adaptee
///
#if !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)
#define EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_
class Adaptee
{
public:
Adaptee();
virtual ~Adaptee();
void specificRequest();
};
#endif // !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)
运行结果:
21、装饰模式(Decrator):动态地给一个对象增加一些额外的职责,就增加的功能来说,该模式相比生成子类更加灵活。
1)模式结构:
装饰模式包含如下角色:Component: 抽象构件、ConcreteComponent: 具体构件、Decorator: 抽象装饰类、ConcreteDecorator: 具体装饰类
2)时序图:
3)代码分析:
///
// ConcreteComponent.cpp
// Implementation of the Class ConcreteComponent
///
#include "ConcreteComponent.h"
#include <iostream>
using namespace std;
ConcreteComponent::ConcreteComponent(){
}
ConcreteComponent::~ConcreteComponent(){
}
void ConcreteComponent::operation(){
cout << "ConcreteComponent's normal operation!" << endl;
}
///
// ConcreteDecoratorA.h
// Implementation of the Class ConcreteDecoratorA
///
#if !defined(EA_6786B68E_DCE4_44c4_B26D_812F0B3C0382__INCLUDED_)
#define EA_6786B68E_DCE4_44c4_B26D_812F0B3C0382__INCLUDED_
#include "Decorator.h"
#include "Component.h"
class ConcreteDecoratorA : public Decorator
{
public:
ConcreteDecoratorA(Component* pcmp);
virtual ~ConcreteDecoratorA();
void addBehavior();
virtual void operation();
};
#endif // !defined(EA_6786B68E_DCE4_44c4_B26D_812F0B3C0382__INCLUDED_)
///
// ConcreteDecoratorA.cpp
// Implementation of the Class ConcreteDecoratorA
///
#include "ConcreteDecoratorA.h"
#include <iostream>
using namespace std;
ConcreteDecoratorA::ConcreteDecoratorA(Component* pcmp)
:Decorator(pcmp)
{
}
ConcreteDecoratorA::~ConcreteDecoratorA(){
}
void ConcreteDecoratorA::addBehavior(){
cout << "addBehavior AAAA" << endl;
}
void ConcreteDecoratorA::operation(){
Decorator::operation();
addBehavior();
}
运行结果:
22、桥接模式(Bridge):将抽象部分与它的实现部分相分离,使它们可以独立变化。
1)模式结构:
桥接模式包含如下角色:Abstraction:抽象类、RefinedAbstraction:扩充抽象类、Implementor:实现类接口、ConcreteImplementor:具体实现类
2)时序图:
3)代码分析:
#include <iostream>
#include "ConcreteImplementorA.h"
#include "ConcreteImplementorB.h"
#include "RefinedAbstraction.h"
#include "Abstraction.h"
using namespace std;
int main(int argc, char *argv[])
{
Implementor * pImp = new ConcreteImplementorA();
Abstraction * pa = new RefinedAbstraction(pImp);
pa->operation();
Abstraction * pb = new RefinedAbstraction(new ConcreteImplementorB());
pb->operation();
delete pa;
delete pb;
return 0;
}
///
// RefinedAbstraction.h
// Implementation of the Class RefinedAbstraction
///
#if !defined(EA_4BA5BE7C_DED5_4236_8362_F2988921CFA7__INCLUDED_)
#define EA_4BA5BE7C_DED5_4236_8362_F2988921CFA7__INCLUDED_
#include "Abstraction.h"
class RefinedAbstraction : public Abstraction
{
public:
RefinedAbstraction();
RefinedAbstraction(Implementor* imp);
virtual ~RefinedAbstraction();
virtual void operation();
};
#endif // !defined(EA_4BA5BE7C_DED5_4236_8362_F2988921CFA7__INCLUDED_)
///
// RefinedAbstraction.cpp
// Implementation of the Class RefinedAbstraction
///
#include "RefinedAbstraction.h"
#include <iostream>
using namespace std;
RefinedAbstraction::RefinedAbstraction(){
}
RefinedAbstraction::RefinedAbstraction(Implementor* imp)
:Abstraction(imp)
{
}
RefinedAbstraction::~RefinedAbstraction(){
}
void RefinedAbstraction::operation(){
cout << "do something else ,and then " << endl;
m_pImp->operationImp();
}
运行结果:
23、享元模式(Flyweight):运用共享技术有效地支持大量细粒度对象的复用。
1)模式结构:
享元模式包含如下角色:Flyweight: 抽象享元类、ConcreteFlyweight: 具体享元类、UnsharedConcreteFlyweight: 非共享具体享元类、FlyweightFactory: 享元工厂类
2)时序图:
3)代码分析:
#include <iostream>
#include "ConcreteFlyweight.h"
#include "FlyweightFactory.h"
#include "Flyweight.h"
using namespace std;
int main(int argc, char *argv[])
{
FlyweightFactory factory;
Flyweight * fw = factory.getFlyweight("one");
fw->operation();
Flyweight * fw2 = factory.getFlyweight("two");
fw2->operation();
//aready exist in pool
Flyweight * fw3 = factory.getFlyweight("one");
fw3->operation();
return 0;
}
///
// FlyweightFactory.cpp
// Implementation of the Class FlyweightFactory
///
#include "FlyweightFactory.h"
#include "ConcreteFlyweight.h"
#include <iostream>
using namespace std;
FlyweightFactory::FlyweightFactory(){
}
FlyweightFactory::~FlyweightFactory(){
}
Flyweight* FlyweightFactory::getFlyweight(string str){
map<string,Flyweight*>::iterator itr = m_mpFlyweight.find(str);
if(itr == m_mpFlyweight.end())
{
Flyweight * fw = new ConcreteFlyweight(str);
m_mpFlyweight.insert(make_pair(str,fw));
return fw;
}
else
{
cout << "aready in the pool,use the exist one:" << endl;
return itr->second;
}
}
///
// ConcreteFlyweight.h
// Implementation of the Class ConcreteFlyweight
///
#if !defined(EA_C0AF438E_96E4_46f1_ADEC_308EF16E11D1__INCLUDED_)
#define EA_C0AF438E_96E4_46f1_ADEC_308EF16E11D1__INCLUDED_
#include "Flyweight.h"
#include <string>
using namespace std;
class ConcreteFlyweight : public Flyweight
{
public:
ConcreteFlyweight(string str);
virtual ~ConcreteFlyweight();
virtual void operation();
private:
string intrinsicState;
};
#endif // !defined(EA_C0AF438E_96E4_46f1_ADEC_308EF16E11D1__INCLUDED_)
///
// ConcreteFlyweight.cpp
// Implementation of the Class ConcreteFlyweight
///
#include "ConcreteFlyweight.h"
#include <iostream>
using namespace std;
ConcreteFlyweight::ConcreteFlyweight(string str){
intrinsicState = str;
}
ConcreteFlyweight::~ConcreteFlyweight(){
}
void ConcreteFlyweight::operation(){
cout << "Flyweight[" << intrinsicState << "] do operation." << endl;
}
运行结果:
时间有限,先写这么多,后面再给出对应类图与代码。