CPP-DesignPattern

前言

简单工厂SimpleFactory

工厂、抽象产品、具体产品

代码

//Factory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Factory 
{
public:
​ Factory();
virtual ~Factory();
static Product * createProduct(string proname);
};

//
Factory::Factory(){
}
Factory::~Factory(){
}
Product* Factory::createProduct(string proname){
if ( "A" == proname )
​ {
return new ConcreteProductA();
​ }
else if("B" == proname)
​ {
return new ConcreteProductB();
​ }
return NULL;
}

//Product

1
2
3
4
5
6
7
8
9
10
11
12
class Product 
{
public:
​ Product();
virtual ~Product();
virtual void Use() = 0;
};

Product::Product(){
}
Product::~Product(){
}

// ConcreteProductA/B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ConcreteProductA : public Product 
{
public:
​ ConcreteProductA();
virtual ~ConcreteProductA();
virtual void Use();
};

ConcreteProductA::ConcreteProductA(){
}
ConcreteProductA::~ConcreteProductA(){
}
void ConcreteProductA::Use()
{
cout << "use productB" << endl;
}

//main.cpp

1
2
3
4
5
6
7
int main(int argc, char *argv[]) 
{
​ Product * prod = Factory::createProduct("A");
​ prod->Use();
delete prod;
return 0;
}

工厂模式FactoryMethod

抽象工厂、抽象产品、具体工厂、具体产品

//Factory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Factory 
{
public:
​ Factory();
virtual ~Factory();
virtual Product* factoryMethod();
};

Factory::Factory(){
}

Factory::~Factory(){
}

Product* Factory::factoryMethod(){
return NULL;
}

//ConcreteFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class ConcreteFactory : public Factory 
{
public:
​ ConcreteFactory();
virtual ~ConcreteFactory();
virtual Product* factoryMethod();
};
//
ConcreteFactory::ConcreteFactory(){
}

ConcreteFactory::~ConcreteFactory(){
}

Product* ConcreteFactory::factoryMethod(){
return new ConcreteProduct();
}

//Client

1
2
3
4
5
6
class Client 
{
public:
​ Client();
virtual ~Client();
};

//ConcreteProduct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ConcreteProduct : public Product 
{
public:
​ ConcreteProduct();
virtual ~ConcreteProduct();
virtual void use();
};

ConcreteProduct::ConcreteProduct(){
}
ConcreteProduct::~ConcreteProduct(){
}
void ConcreteProduct::use(){
cout << "use prodect A" << endl;
}

//main

1
2
3
4
5
6
7
8
9
10
int main(int argc, char *argv[]) 
{
​ Factory * fc = new ConcreteFactory();
​ Product * prod = fc->factoryMethod();
​ prod->use();

delete fc;
delete prod;
return 0;
}

抽象工厂AbstractFactory

//AbstractProductA/B

1
2
3
4
5
6
7
class AbstractProductA 
{
public:
​ AbstractProductA();
virtual ~AbstractProductA();
virtual void use() = 0;
};

//具体产品A1/2,B1/2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ProductA1 : public AbstractProductA 
{
public:
​ ProductA1();
virtual ~ProductA1();
void use();
};

ProductA1::ProductA1(){
}
ProductA1::~ProductA1(){
}
void ProductA1::use(){
cout << "use Product A1" << endl;
}

//具体工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class ConcreteFactory1 : public AbstractFactory 
{
public:
​ ConcreteFactory1();
virtual ~ConcreteFactory1();
virtual AbstractProductA * createProductA();
virtual AbstractProductB * createProductB();
};


ConcreteFactory1::ConcreteFactory1(){
}

ConcreteFactory1::~ConcreteFactory1(){
}

AbstractProductA * ConcreteFactory1::createProductA(){
return new ProductA1();
}

AbstractProductB * ConcreteFactory1::createProductB(){
return new ProductB1();
}

//AbstractFactory

1
2
3
4
5
6
7
8
class AbstractFactory 
{
public:
​ AbstractFactory();
virtual ~AbstractFactory();
virtual AbstractProductA * createProductA() = 0;
virtual AbstractProductB * createProductB() = 0;
};

//main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();

delete fc;
delete pa;
delete pb;
delete fc2;
delete pa2;
delete pb2;

return 0;
}

Builder

//指挥者
class Director
{
public:
​ Director();
​ virtual ~Director();
​ Builder m_Builder;
​ Product
constuct();
​ void setBuilder(Builder buider);
private:
​ Builder
m_pbuilder;
};

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;
}

//抽象建造者
class Builder
{
public:
​ Builder();
​ virtual ~Builder();
​ virtual void buildPartA();
​ virtual void buildPartB();
​ virtual void buildPartC();
​ virtual Product * getResult();

protected :
​ Product * m_prod;
};

Builder::Builder(){
​ m_prod = new Product();
}
Builder::~Builder(){
}
void Builder::buildPartA(){
}
void Builder::buildPartB(){
}
void Builder::buildPartC(){
}
Product* Builder::getResult(){
​ return m_prod;
}

//具体建造者

class ConcreteBuilder : public Builder
{
public:
​ ConcreteBuilder();
​ virtual ~ConcreteBuilder();
​ virtual void buildPartA();
​ virtual void buildPartB();
​ virtual void buildPartC();
};

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 “);
}

//产品

class Product
{
public:
​ Product();
​ virtual ~Product();
​ void setA(string str);
​ void setB(string str);
​ void setC(string str);
​ void show();

private:

​ string m_a;
​ string m_b;
​ string m_c;
};

Product::Product(){
}

Product::~Product(){
}

void Product::setA(string str)
{
​ m_a = str;
}

void Product::setB(string str)
{
​ m_b = str;
}

void Product::setC(string str)
{
​ m_c = str;
}

void Product::show()
{
​ cout << “product has” << m_a << m_b << m_c << endl;
}

//main

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;
}

单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class LazySingleton { 
//私有,静态的类自身实例
//初始为null,暂不实例化
private static LazySingleton instance = null;

//私有的构造子(构造器,构造函数,构造方法)
private LazySingleton(){}

//公开,静态的工厂方法,需要使用时才去创建该单体
public static LazySingleton getInstance() {
if( instance == null ) {
​ instance = new LazySingleton();
​ }
return instance;
​ }
}

注意:
现在很多面向对象语言(如Java、C#)的运行环境都提供了自动垃圾回收的技术,因此,如果实例化的对象长时间不被利用,系统会认为它是垃圾,会自动销毁并回收资源,下次利用时又将重新实例化,这将导致对象状态的丢失。

结构型
结构型模式(Structural Pattern)描述如何将类或者对 象结合在一起形成更大的结构,就像搭积木,可以通过简单积木的组合形成复杂的、功能更为强大的结构。

结构型模式可以分为类结构型模式和对象结构型模式:

类结构型模式
关心类的组合,由多个类可以组合成一个更大的系统,在类结构型模式中一般只存在继承关系和实现关系。

对象结构型模式
关心类与对象的组合,通过关联关系使得在一个类中定义另一个类的实例对象,然后通过该对象调用其方法。根据“合成复用原则”,在系统中尽量使用关联关系来替代继 承关系,因此大部分结构型模式都是对象结构型模式。

适配器Adaptor

adaptor适配器
adapted需要适配的类,不暴露给用户
四个类:
客户Client
目标抽象类Target
适配器Adaptor
适配者Adaptee

//Target

1
2
3
4
5
6
7
8
9
10
11
class Target 
{
public:
​ Target();
virtual ~Target();
virtual void request();
};

void Target::request(){
cout << "this is original request " << endl;
}

//Adapter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Adapter : public Target 
{
public:
​ Adapter(Adaptee *adaptee);
virtual ~Adapter();
virtual void request();

private:
​ Adaptee* m_pAdaptee;
};

Adapter::Adapter(Adaptee * adaptee){
​ m_pAdaptee = adaptee;
}

Adapter::~Adapter(){
}

void Adapter::request(){
​ m_pAdaptee->specificRequest();
}

//adaptee

1
2
3
4
5
6
7
8
9
10
11
class Adaptee 
{
public:
​ Adaptee();
virtual ~Adaptee();
void specificRequest();
};

void Adaptee::specificRequest(){
cout << "specificRequest()|this is real Request from Adaptee!" << endl;
}

//main

1
2
3
4
5
6
7
int main(int argc, char *argv[]) 
{
​ Adaptee * adaptee = new Adaptee();
​ Target * tar = new Adapter(adaptee);
​ tar->request();
return 0;
}

桥接关系

将继承关系转化成关联关系。如绘制四个形状,四种颜色,考虑桥接。将抽象和实现分离开来。

Abstraction:抽象类
RefinedAbstraction:扩充抽象类
Implementor:实现类接口
ConcreteImplementor:具体实现类
//main

1
2
3
4
5
6
7
8
9
10
11
12
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;
}

//Abstraction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Abstraction 
{
public:
​ Abstraction();
virtual ~Abstraction();
​ Abstraction(Implementor* imp);
virtual void operation();
protected:
​ Implementor* m_pImp;
};

Abstraction::Abstraction(){
}

Abstraction::~Abstraction(){
delete m_pImp;
}

Abstraction::Abstraction(Implementor* imp){
​ m_pImp = imp;
}

void Abstraction::operation(){
}

//RefinedAbstraction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class RefinedAbstraction : public Abstraction 
{
public:
​ RefinedAbstraction();
​ RefinedAbstraction(Implementor* imp);
virtual ~RefinedAbstraction();
virtual void operation();
};

RefinedAbstraction::RefinedAbstraction(){
}

RefinedAbstraction::RefinedAbstraction(Implementor* imp)
​ :Abstraction(imp){
}

这里做的实际上是基类的初始化。
RefinedAbstraction::~RefinedAbstraction(){
}

void RefinedAbstraction::operation(){
cout << "do something else ,and then " << endl;
​ m_pImp->operationImp();
}

//Implementor

1
2
3
4
5
6
7
8
9
class Implementor 
{
public:
​ Implementor();
virtual ~Implementor();
virtual void operationImp();
};

空实现

//ConcreteImplementorA/B具体实现类

1
2
3
4
5
6
7
8
9
10
11
class ConcreteImplementorA : public Implementor 
{
public:
​ ConcreteImplementorA();
virtual ~ConcreteImplementorA();
virtual void operationImp();
};

void ConcreteImplementorA::operationImp(){
cout << "imp in ConcreteImplementorA style." << endl;
}

装饰器

Component是定义一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,
Component来说,是无需知道Decorator的存在的。
ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。

要善于变通,如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。

同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为 的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为 时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

//Component

1
2
3
4
5
6
7
class Component 
{
public:
​ Component();
virtual ~Component();
virtual void operation();
};空实现

//ConcreteComponent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ConcreteComponent : public Component 
{
public:
​ ConcreteComponent();
virtual ~ConcreteComponent();
void operation();
};

ConcreteComponent::ConcreteComponent(){
}
ConcreteComponent::~ConcreteComponent(){
}
void ConcreteComponent::operation(){
cout << "ConcreteComponent's normal operation!" << endl;
}

//Decorator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Decorator : public Component 
{
public:
​ Decorator(Component* pcmp);
virtual ~Decorator();
void operation();
private:
​ Component * m_pComponent;
};

Decorator::Decorator(Component* pcmp){
​ m_pComponent = pcmp;
}
Decorator::~Decorator(){
}
void Decorator::operation(){
​ m_pComponent->operation();
}

//ConcreteDecoratorA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ConcreteDecoratorA : public Decorator 
{
public:
​ ConcreteDecoratorA(Component* pcmp);
virtual ~ConcreteDecoratorA();
void addBehavior();
virtual void operation();
};

ConcreteDecoratorA::ConcreteDecoratorA(Component* pcmp)
:Decorator(pcmp){
}
ConcreteDecoratorA::~ConcreteDecoratorA(){
}
void ConcreteDecoratorA::addBehavior(){
cout << "addBehavior AAAA" << endl;
}
void ConcreteDecoratorA::operation(){
​ Decorator::operation();
​ addBehavior();
}

int main(int argc, char *argv[])
{
​ ConcreteComponent pRealProd = new ConcreteComponent();
​ //动态增加行为
​ Component
pA = new ConcreteDecoratorA(pRealProd);
​ pA->operation();
​ //继续动态增加行为
​ Component * pB = new ConcreteDecoratorB(pA);
​ pB->operation();

​ delete pRealProd;
​ delete pA;
​ delete pB;
​ return 0;
}
输出:
cnp
AAA
cnp
AAA
BBB

外观模式

//main

1
2
3
4
5
6
int main(int argc, char *argv[]) 
{
​ Facade fa;
​ fa.wrapOpration();
return 0;
}

//Facade

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Facade 
{
public:
​ Facade();
virtual ~Facade();
void wrapOpration();
private:
​ SystemC *m_SystemC;
​ SystemA *m_SystemA;
​ SystemB *m_SystemB;
};

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();
}

//SystemA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SystemA 
{
public:
​ SystemA();
virtual ~SystemA();
void operationA();
};

SystemA::SystemA(){
}
SystemA::~SystemA(){
}

void SystemA::operationA(){
cout << "operationA" << endl;
}

享元模式//不是很明白

享元模式是一个考虑系统性能的设计模式,通过使用享元模式可以节约内存空间,提高系统的性能。

享元模式的核心在于享元工厂类,享元工厂类的作用在于提供一个用于存储享元对象的享元池,用户需要对象时,首先从享元池中获取,如果享元池中不存在,则创建一个新的享元对象返回给用户,并在享元池中保存该新增对象。

享元模式以共享的方式高效地支持大量的细粒度对象,享元对象能做到共享的关键是区分内部状态(Internal State)和外部状态(External State)。

内部状态是存储在享元对象内部并且不会随环境改变而改变的状态,因此内部状态可以共享。

外部状态是随环境改变而改变的、不可以共享的状态。享元对象的外部状态必须由客户端保存,并在享元对象被创建之后,在需要使用的时候再传入到享元对象内部。一个外部状态与另一个外部状态之间是相互独立的。
//main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}

//Flyweight

1
2
3
4
5
6
7
8
9
10
11
12
class Flyweight{ 
public:
​ Flyweight();
virtual ~Flyweight();
virtual void operation();
};



Flyweight::Flyweight(){}
Flyweight::~Flyweight(){}
void Flyweight::operation(){}

//FlyweightFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class FlyweightFactory{ 
public:
​ FlyweightFactory();
virtual ~FlyweightFactory();
Flyweight* getFlyweight(string str);
private:
map<string,Flyweight*> m_mpFlyweight;
};



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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ConcreteFlyweight : public Flyweight{ 
public:
​ ConcreteFlyweight(string str);
virtual ~ConcreteFlyweight();
virtual void operation();
private:
string intrinsicState;
};

ConcreteFlyweight::ConcreteFlyweight(string str){
​ intrinsicState = str;
}

ConcreteFlyweight::~ConcreteFlyweight(){}

void ConcreteFlyweight::operation(){

cout << "Flyweight[" << intrinsicState << "] do operation." << endl;
}

//UnsharedConcreteFlyweight

1
2
3
4
5
6
7
8
9
10
11
12
class UnsharedConcreteFlyweight : public Flyweight{ 
public:
​ UnsharedConcreteFlyweight();
virtual ~UnsharedConcreteFlyweight();
void operation();
private:
int allState;
};

UnsharedConcreteFlyweight::UnsharedConcreteFlyweight(){}
UnsharedConcreteFlyweight::~UnsharedConcreteFlyweight(){}
void UnsharedConcreteFlyweight::operation(){}

代理模式

主要有三个角色:

Subject:
Proxy:
Realsubject:
//

1
2
3
4
5
int main(int argc, char *argv[]){ 
​ Proxy proxy;
​ proxy.request();
return 0;
}

//subject 接口

1
2
3
4
5
6
7
8
class Subject{ 
public:
​ Subject();
virtual ~Subject();
virtual void request();
};

空实现

//RealSubject

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class RealSubject : public Subject{ 
public:
​ RealSubject();
virtual ~RealSubject();
void request();
};



RealSubject::RealSubject(){}
RealSubject::~RealSubject(){}
void RealSubject::request(){
cout << "RealSubject::request" << endl;
}

//Proxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Proxy : public Subject{ 
public:
​ Proxy();
virtual ~Proxy();
void request();
private:
void afterRequest();
void preRequest();
​ RealSubject *m_pRealSubject;
};

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();
}

命令模式

Command: 抽象命令类
ConcreteCommand: 具体命令类
Invoker: 调用者
Receiver: 接收者
Client:客户类

//main

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Receiver{ 
public:
​ Receiver();
virtual ~Receiver();
void action();
};

Receiver::Receiver(){}

Receiver::~Receiver(){}

void Receiver::action(){
cout << "receiver action." << endl;
}

//Command

1
2
3
4
5
6
7
class Command{ 
public:
​ Command();
virtual ~Command();
virtual void execute();
};
空实现

//ConcreteCommand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ConcreteCommand : public Command{ 
public:
​ ConcreteCommand(Receiver * pReceiver);
virtual ~ConcreteCommand();
virtual void execute();
private:
​ Receiver *m_pReceiver;
};

ConcreteCommand::ConcreteCommand(Receiver *pReceiver){
​ m_pReceiver = pReceiver;
}

ConcreteCommand::~ConcreteCommand(){}

void ConcreteCommand::execute(){
cout << "ConcreteCommand::execute" << endl;
​ m_pReceiver->action();
}

//Invoker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Invoker{ 
public:
​ Invoker(Command * pCommand);
virtual ~Invoker();
void call();
private:
​ Command *m_pCommand;
};



Invoker::Invoker(Command * pCommand){
​ m_pCommand = pCommand;
}

Invoker::~Invoker(){}
void Invoker::call(){
cout << "invoker calling" << endl;
​ m_pCommand->execute();
}

中介模式

中介者模式(Mediator Pattern)定义:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式又称为调停者模式,它是一种对象行为型模式。

Colleage抽象同事类,而ConcreteColleage是具体同时类,每个具体同事只知道自己的行为,而不了解其他同事类的情况,但它们却都认识中介者对象,Mediator是抽象中介者,定义了同事对象到中介者对象的接口,ConcreteMediator是具体中介者对象,实现抽象类的方法,它需要知道所有具体同事类,并从具体同事接受消息,向具体同事对象发出命令。

Colleage类,抽象同事类

Mediator,抽象中介者类

说明:

\1. Mediator 模式中,每个Colleague 维护一个 Mediator,当要进行通信时,每个具体的 Colleague 直接向ConcreteMediator 发信息,至于信息发到哪里,则由 ConcreteMediator 来决定。

\2. ConcreteColleagueA 和 ConcreteColleagueB 不必维护对各自的引用,甚至它们也不知道各个的存在。

\3. 优点是,各个 Colleague 减少了耦合。

\4. 缺点是,由于 Mediator 控制了集中化,于是就把 Colleague 之间的交互复杂性变为了中介者的复杂性,也就是中介者会变的比任何一个 Colleague 都复杂。

中介者模式很容易在系统中应用,也很容易在系统中误用。当系统中出现了“多对多”交互复杂的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是不是合理。

Mediator的出现减少了各个Colleage的耦合,使得可以独立地改变和复用各个Colleage类和Mediator;

由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。

由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这使得中介者会变得比任何一个ConcreteColleage都复杂。

中介者模式的优点来自集中控制,其缺点也是它。

中介者模式一般应用于一组对象以定义良好但是复杂的方式进行通信的场合。

举例,虚拟聊天室

某论坛系统欲增加一个虚拟聊天室,允许论坛会员通过该聊天室进行信息交流,普通会员(CommonMember)可以给其他会员发送文本信息,钻石会员(DiamondMember)既可以给其他会员发送文本信息,还可以发送图片信息。该聊天室可以对不雅字符进行过滤,如“日”等字符;还可以对发送的图片大小进行控制。

主要有四个类,抽象中介/具体中介,抽象同事/具体同事

//main

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

//Mediator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Mediator{ 
public:
​ Mediator();
virtual ~Mediator();
virtual void operation(int nWho,string str);
virtual void registered(int nWho, Colleague * aColleague);
};



Mediator::Mediator(){}

Mediator::~Mediator(){}

void Mediator::operation(int nWho,string str){}

void Mediator::registered(int nWho,Colleague * aColleague){}

//ConcreteMediator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
};

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);
​ }
}

//Colleague

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Colleague{ 

public:
​ Colleague();
virtual ~Colleague();
virtual void receivemsg(string str);
virtual void sendmsg(int toWho,string str);
void setMediator(Mediator * aMediator);
protected:
​ Mediator * m_pMediator;
};

Colleague::Colleague(){}

Colleague::~Colleague(){}

void Colleague::receivemsg(string str){
cout << "reveivemsg:" << str <<endl;
}

void Colleague::sendmsg(int toWho,string str){}

void Colleague::setMediator(Mediator * aMediator){
​ m_pMediator = aMediator;
}

//ConcreteColleagueA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class ConcreteColleagueA : public Colleague{ 

public:
​ ConcreteColleagueA();
virtual ~ConcreteColleagueA();
virtual void sendmsg(int toWho,string str);
virtual void receivemsg(string str);
};

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;
}

观察者模式

MVC框架,省略

状态模式

Context: 环境类

State: 抽象状态类

ConcreteState: 具体状态类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Context 
{
public:
​ Context();
virtual ~Context();
void changeState(State * st);
void request();

private:
​ State *m_pState;
};

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);
}

//State

1
2
3
4
5
6
7
8
class State{ 
public:
​ State();
virtual ~State();
virtual void handle(Context * c);
};

空实现

//ConcreteStateA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class ConcreteStateA : public State{ 
public:
virtual ~ConcreteStateA();
static State * Instance();
virtual void handle(Context * c);

private:
​ ConcreteStateA();
static State * m_pState;
};

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());
}

举例实现,一个TCP协议

策略模式

用不同的类封装不同的解决方案/算法策略,实际上编码本省的核心或者说前提条件就是,解决好解决方案或者方法的策略,设计。

环境类 Context
抽象策略类 Strategy
具体策略类 ConcreteStrategy

//main

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
return 0;
}

//Context

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Context 
{
public:
​ Context();
virtual ~Context();
void algorithm();
void setStrategy(Strategy* st);
private:
​ Strategy *m_pStrategy;
};

Context::Context() {}
Context::~Context() {}
void Context::algorithm() {
​ m_pStrategy->algorithm();
}
void Context::setStrategy(Strategy* st) {
​ m_pStrategy = st;
}

//Strategy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Strategy 
{
public:
​ Strategy();
virtual ~Strategy();
virtual void algorithm();
};

Strategy::Strategy() {}
Strategy::~Strategy() {}
void Strategy::algorithm() {}

**//ConcreteStrategy**
class ConcreteStrategyA : public Strategy
{
public:
​ ConcreteStrategyA();
virtual ~ConcreteStrategyA();
virtual void algorithm();
};

ConcreteStrategyA::ConcreteStrategyA() {}
ConcreteStrategyA::~ConcreteStrategyA() {}
void ConcreteStrategyA::algorithm() {
cout << "use algorithm A" << endl;
}

输出:
两个算法的分别使用。