目录
A. 设计原则
B. 设计模式分类
1. 从目的来看:
2. 从范围来看:
3. 从封装变化角度进行分类:
C. 设计模式类图与实例
1. 组件协作
策略模式Strategy
模板方法模式TemplateMethod
观察者模式Observer
2. 单一职责
装饰者模式Decorator
桥接模式Birdge
3. 对象创建
工厂方法模式FactoryMethod
抽象工厂模式AbstractFactory
原型模式Prototype
构造器模式Builder(低频)
4. 对象性能
单例模式Singleton
享元模式Flyweight
5. 接口隔离
门面模式Facade
代理模式Proxy编辑
适配器模式Adapter
中介者模式Mediator(低频)
6. 状态变化
状态模式State
备忘录模式Memento(低频)
7. 数据结构
组合模式Composite
迭代器模式Iterator(低频)
职责链模式ChainOfResponsibility(低频)
8. 行为变化
命令行模式Command(低频)
访问器模式Visitor(低频)
9. 领域规则
解释器模式Interpreter(低频)
【单一职责原则SRP】实现类要职责单一
【里氏替换原则LSP】不要破坏继承体系
【依赖倒置原则DIP】面向抽象编程
【接口隔离原则ISP】设计接口要精简单一
【迪米特法则LoD】要降低耦合度
【开闭原则OCP】对修改关闭,对扩展开放(解耦、单一、高内聚就是开闭原则的精神纲领)
【优先使用组合,而不是类继承】
【封装变化点】
【针对接口编程,而不是针对实现编程】
- 创建型模式:将对象的部分创建工作延迟到子类或者其它对象,从而应对需求变化为对象创建时具体实现引来的冲击。
- Singleton、Simple Factory、Factory Method、Abstract Factory、Builder、Prototype。
- 结构型模式:通过类继承或者对象组合获得更灵活的结构,从而应对需求变化为对象的结构带来的冲击。
- Adapter、Composite、Decorator、Proxy、Flyweight、Facade、Bridge。
- 行为型模式:通过类继承或者对象组合划分类与对象间的职责,从而应对需求变化为多个交互的对象带来的冲击。
- Template Method、Interpreter、Strategy、State、Observer、Memento、Command、Mediator、Visitor、ChainOfResposibility、Iterator。
- 类模式处理类与子类的静态关系(更偏向于继承方案)
- 对象模式处理对象间的动态关系(更偏向于对象组合方案)
- 组件协作:Template Method、Strategy、Observer/Event
- 单一职责:Decorator、Bridge
- 对象创建:Factory Method、Abstract Factory、Prototype、Builder
- 对象性能:Singleton、Flyweight
- 接口隔离:Facade、Proxy、Mediator、Adapter
- 状态变化:Memento、State
- 数据结构:Composite、Iterator、Chain of Responsibility
- 行为变化:Command、Visitor
- 领域问题:Interpreter
#include
#include
using namespace std;
#define DELETE_PTR( ptr ) { if( ptr ) { delete ptr; ptr = nullptr; } }
#define PRINT_FUNC printf("execute func = %s\n" , __FUNCTION__);
#define PRINT_INFO( str ) printf("info = %s\n" , str);
//#define DELETE_PTR( ptr ) ( if( ptr ) { delete ptr; ptr = nullptr; } ) //error
//#define PRINT_FUNC; printf("execute file:%s\tline:%d\t \
// date:%s\ttime:%s\t \
// func:%s\n" ,\
// __FILE__,__LINE__ , \
// __DATE__,__TIME__ , __FUNCTION__)
//
/*
* 组件协作模式:策略模式,解决的是一个对象有多种算法或者操作需要切换
*/
namespace StrategyPattern {
//抽象算法类
class IStrategy {
public:
virtual ~IStrategy() { PRINT_FUNC; }
virtual void AlgorithmInterface() = 0;
};
//具体算法类
class ConcreteStratergyA : public IStrategy {
public:
virtual ~ConcreteStratergyA() { PRINT_FUNC; }
virtual void AlgorithmInterface() override
{
PRINT_FUNC;
}
};
class ConcreteStratergyB : public IStrategy {
public:
virtual ~ConcreteStratergyB() { PRINT_FUNC; }
virtual void AlgorithmInterface() override
{
PRINT_FUNC;
}
};
/*
class ConcreteStratergy[......] : public IStrategy {
};
*/
class Context {
public:
Context(IStrategy* stratergy) : m_pStratergy(stratergy) {}
virtual ~Context()
{
PRINT_FUNC;
DELETE_PTR(m_pStratergy)
}
void ContextInterface()
{
m_pStratergy->AlgorithmInterface();
}
private:
IStrategy* m_pStratergy;
};
void executeStratergy()
{
IStrategy* stratergy = new ConcreteStratergyA;
Context* context = new Context(stratergy);
context->ContextInterface();
delete context;
context = nullptr;
stratergy = new ConcreteStratergyB;
context = new Context(stratergy);
context->ContextInterface();
delete context;
context = nullptr;
}
}
//
/*
* 组件协作模式:模板方法模式,基类中定义了一套稳定的操作步骤,把各个步骤延迟到各个派生类去实现
*/
#include // typeid need
namespace TemplateMethodPattern {
class AbstractClass
{
public:
void Execute() //Template Method
{
Step1();
Step2();
}
protected:
virtual void Step1() = 0;
virtual void Step2() = 0;
};
class ConcreteClassA : public AbstractClass
{
protected:
virtual void Step1() override
{
/********************************/
PRINT_FUNC;
/********************************/
}
virtual void Step2() override
{
/********************************/
PRINT_FUNC;
/********************************/
}
};
class ConcreteClassB : public AbstractClass
{
public:
protected:
virtual void Step1() override
{
//
PRINT_FUNC;
//
}
virtual void Step2() override
{
//
PRINT_FUNC;
//
}
};
void executeTemplateMethod()
{
AbstractClass* a = new ConcreteClassB;
a->Execute();
}
}
//
/*
* 组件协作模式:观察者模式,建立一种通知依赖,目标状态发生改变,所有依赖对象(观察者)跟着收到状态改变。
*/
#include
namespace ObserverPattern {
class IObserver
{
public:
virtual void Update(const string& info) = 0;
};
class ObserverA : public IObserver {
public:
virtual void Update(const string& info) override
{
PRINT_FUNC;
PRINT_INFO(info.c_str());
}
};
class ObserverB : public IObserver {
public:
virtual void Update(const string& info) override
{
PRINT_FUNC;
PRINT_INFO(info.c_str());
}
};
class Subject
{
public:
void AddObserver(IObserver* obs)
{
auto iter = find(m_Observers.begin(), m_Observers.end(), obs);
if (iter != m_Observers.end())
{
return;//已存在
}
m_Observers.push_back(obs);
}
void DelObserver(IObserver* obs)
{
//m_Observers.remove(obs);
auto iter = find(m_Observers.begin(), m_Observers.end(), obs);
if (iter != m_Observers.end())
{
m_Observers.erase(iter);
}
else {
PRINT_INFO("没有该对象");
}
}
void Notify(const string& info)
{
PRINT_FUNC;
PRINT_INFO(info.c_str());
for (auto obs : m_Observers)
{
obs->Update(info);
}
}
private:
list m_Observers;
};
void executeObserver()
{
Subject* subject = new Subject;
IObserver* observer = new ObserverA;
subject->AddObserver(observer);
subject->DelObserver(observer);
observer = new ObserverB;
subject->AddObserver(observer);
subject->Notify(string("今晚吃大餐"));
}
}
//
/*
* 单一职责模式:装饰者模式,Decorator在接口上是一种is-a-component,在实现上一种has-a-component。解决了主体类在多个方向上的扩展
*/
namespace DecoratorPattern {
class AbstractComponent {
public:
virtual void Operation() = 0;
};
class ConcreteComponent : public AbstractComponent
{
public:
virtual void Operation() override
{
PRINT_INFO("具体组件...");
PRINT_FUNC;
}
};
class Decorator : public AbstractComponent {
public:
Decorator(AbstractComponent* comp) : m_pAbsComp(comp) {}
virtual ~Decorator()
{
DELETE_PTR(m_pAbsComp);
}
virtual void Operation() override
{
PRINT_FUNC;
m_pAbsComp->Operation();
}
private:
AbstractComponent* m_pAbsComp;
};
class ConcreteDecoratorA : public Decorator
{
public:
ConcreteDecoratorA(AbstractComponent* comp) : Decorator(comp) {}
virtual void Operation() override
{
PRINT_INFO("装饰A...");
PRINT_FUNC;
Decorator::Operation();
}
};
class ConcreteDecoratorB : public Decorator
{
public:
ConcreteDecoratorB(AbstractComponent* comp) : Decorator(comp) {}
virtual void Operation() override
{
PRINT_INFO("装饰B...");
PRINT_FUNC;
Decorator::Operation();
}
};
void executeDecorator()
{
//单纯组件
AbstractComponent* comp = new ConcreteComponent;
comp->Operation();
cout << endl;
//用A装饰组件
Decorator* decoratorA = new ConcreteDecoratorA(comp);
decoratorA->Operation();
cout << endl;
//用A+B装饰组件
Decorator* decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB->Operation();
}
}
//
/*
* 单一职责模式:桥接模式,用于解决类在两个维度上的变化,将抽象业务和具体实现相分离。
*/
namespace BridgePattern {
class AbstractImplementor {
public:
virtual void Operation() = 0;
};
class ConcreteImplementorA : public AbstractImplementor {
public:
virtual void Operation()
{
PRINT_FUNC;
}
};
class ConcreteImplementorB : public AbstractImplementor {
public:
virtual void Operation()
{
PRINT_FUNC;
}
};
class AbstractBusiness {
public:
AbstractBusiness(AbstractImplementor* imp) : m_pImp(imp) {}
virtual ~AbstractBusiness()
{
DELETE_PTR(m_pImp);
}
virtual void Operation() = 0;
protected:
AbstractImplementor* m_pImp;
};
class ConcreteBusinessA : public AbstractBusiness {
public:
ConcreteBusinessA(AbstractImplementor* imp) : AbstractBusiness(imp) {}
virtual void Operation()
{
PRINT_FUNC;
m_pImp->Operation();
}
};
class ConcreteBusinessB : public AbstractBusiness {
public:
ConcreteBusinessB(AbstractImplementor* imp) : AbstractBusiness(imp) {}
virtual void Operation()
{
PRINT_FUNC;
m_pImp->Operation();
}
};
void executeBridge()
{
AbstractImplementor* m_pImp = new ConcreteImplementorA;
AbstractBusiness* business = new ConcreteBusinessA(m_pImp);
business->Operation();
cout << endl;
m_pImp = new ConcreteImplementorB;
business = new ConcreteBusinessA(m_pImp);
business->Operation();
}
}
//
/*
* 对象创建模式:工厂方法模式,通过“对象创建”绕开new,避免new过程中的紧耦合。
*/
namespace FactoryMethod {
class AbstractProduct {
public:
virtual void Operation() = 0;
};
class ConcreteProductA : public AbstractProduct
{
public:
virtual void Operation()
{
PRINT_INFO("产品A......");
}
};
class ConcreteProductB : public AbstractProduct
{
public:
virtual void Operation()
{
PRINT_INFO("产品B......");
}
};
class AbstractFactory
{
public:
void AnOperation()
{
AbstractProduct* product = CreateProduct();
product->Operation();
}
protected:
virtual AbstractProduct* CreateProduct() = 0;
};
class ConcreteFactoryA : public AbstractFactory
{
public:
virtual AbstractProduct* CreateProduct()
{
return new ConcreteProductA;
}
};
class ConcreteFactoryB : public AbstractFactory
{
public:
virtual AbstractProduct* CreateProduct()
{
return new ConcreteProductB;
}
};
void executeFactoryMethod()
{
AbstractFactory* factory = new ConcreteFactoryA;
factory->AnOperation();
cout << endl;
factory = new ConcreteFactoryB;
factory->AnOperation();
}
}
//
/*
* 对象创建模式:抽象工厂模式,解决的是一系列相互依赖的对象的创建。
*/
namespace AbstractFactory
{
class AbstractProductA
{
public:
virtual void Operation() = 0;
};
class AbstractProductB
{
public:
virtual void Operation() = 0;
};
class ProductPartA1 : public AbstractProductA
{
public:
virtual void Operation()
{
PRINT_INFO("产品零部件A1......");
}
};
class ProductPartA2 : public AbstractProductA
{
public:
virtual void Operation()
{
PRINT_INFO("产品零部件A2......");
}
};
class ProductPartB1 : public AbstractProductB
{
public:
virtual void Operation()
{
PRINT_INFO("产品零部件B1......");
}
};
class ProductPartB2 : public AbstractProductB
{
public:
virtual void Operation()
{
PRINT_INFO("产品零部件B2......");
}
};
class AbstractFactory
{
public:
void AnOperation()
{
m_ProductA = CreateProductA();
m_ProductA->Operation();
m_ProductB = CreateProductB();
m_ProductB->Operation();
}
virtual AbstractProductA* CreateProductA() = 0;
virtual AbstractProductB* CreateProductB() = 0;
protected:
AbstractProductA* m_ProductA;
AbstractProductB* m_ProductB;
};
//工厂A生产产品A,由产品A零部件1+产品A零部件2组成
class ConcreteFactroy1 : public AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA()
{
return new ProductPartA1;
}
virtual AbstractProductB* CreateProductB()
{
return new ProductPartB1;
}
};
//工厂B生产产品B,由产品B零部件1+产品B零部件2组成
class ConcreteFactroy2 : public AbstractFactory
{
public:
virtual AbstractProductA* CreateProductA()
{
return new ProductPartA2;
}
virtual AbstractProductB* CreateProductB()
{
return new ProductPartB2;
}
};
void executeAbstractFactory()
{
PRINT_INFO("工厂1......");
AbstractFactory* factory = new ConcreteFactroy1;
factory->AnOperation();
PRINT_INFO("工厂2......");
factory = new ConcreteFactroy2;
factory->AnOperation();
}
}
//
/*
* 对象创建模式:原型模式,使用原型实例指定创建对象的种类,通过深拷贝原型来创建新对象。类似现实中的配钥匙店铺提供配钥匙的服务,但是需要顾客自己带着原型钥匙,才能配出新钥匙。
* 通过不同派生类实现clone接口函数,可以完成与“虚拟构造函数”同样的效果。
*/
namespace Prototype {
class IPrototype
{
public:
virtual IPrototype* Clone() = 0;
};
class ConcretePrototype1 : public IPrototype
{
public:
ConcretePrototype1()
{
cout << "无参构造缓函数:";
PRINT_FUNC;
}
ConcretePrototype1(const ConcretePrototype1& prototype)
{
cout << "拷贝构造缓函数:";
PRINT_FUNC;
}
virtual IPrototype* Clone() override
{
return new ConcretePrototype1(*this);
}
};
class ConcretePrototype2 : public IPrototype
{
public:
ConcretePrototype2()
{
cout << "无参构造缓函数:";
PRINT_FUNC;
}
ConcretePrototype2(const ConcretePrototype2& prototype)
{
cout << "拷贝构造缓函数:";
PRINT_FUNC;
}
virtual IPrototype* Clone() override
{
return new ConcretePrototype2(*this);
}
};
class Client {
public:
Client(IPrototype* prototype) : m_pPrototype(prototype) {}
virtual ~Client()
{
DELETE_PTR(m_pPrototype);
}
IPrototype* Operation()
{
return m_pPrototype->Clone();
}
private:
IPrototype* m_pPrototype;
};
void executePrototype()
{
IPrototype* Prototype1Obj = new ConcretePrototype1;
IPrototype* clonePrototype1Obj = Prototype1Obj->Clone();
IPrototype* Prototype2Obj = new ConcretePrototype2;
IPrototype* clonePrototype2Obj = Prototype2Obj->Clone();
}
}
//
/*
* 对象创建模式:构构建器模式,一个对象由多个部分组成,而各个部分又经常需要改变
*/
namespace Builder
{
class IHouse {
public:
IHouse()
{
PRINT_FUNC;
}
virtual ~IHouse() { PRINT_FUNC; }
virtual void BuildRoof() = 0;
virtual void BuildWall() = 0;
virtual void BuildWindow() = 0;
virtual void BuildDoor() = 0;
virtual void BuildGround() = 0;
};
class IBuilder
{
public:
IBuilder() { PRINT_FUNC; }
virtual ~IBuilder()
{
PRINT_FUNC;
}
virtual IHouse* CreateHouse()
{
IHouse* house = GetHouse();
PRINT_INFO("开始组装...");
BuildRoof(house);
BuildWall(house);
BuildWindow(house);
BuildDoor(house);
BuildGround(house);
return house;
}
virtual IHouse* GetHouse() = 0;
private:
virtual void BuildRoof(IHouse* house) = 0;
virtual void BuildWall(IHouse* house) = 0;
virtual void BuildWindow(IHouse* house) = 0;
virtual void BuildDoor(IHouse* house) = 0;
virtual void BuildGround(IHouse* house) = 0;
};
///
class StoneHouse : public IHouse
{
public:
StoneHouse()
{
PRINT_FUNC;
}
virtual ~StoneHouse()
{
PRINT_FUNC;
}
virtual void BuildRoof()
{
cout << "\t生成人字形屋顶...";
PRINT_FUNC;
}
virtual void BuildWall()
{
cout << "\t生成四面围墙...";
PRINT_FUNC;
}
virtual void BuildWindow()
{
cout << "\t生成四个窗户...";
PRINT_FUNC;
}
virtual void BuildDoor()
{
cout << "\t生成两扇门...";
PRINT_FUNC;
}
virtual void BuildGround()
{
cout << "\t生成木地面...";
PRINT_FUNC;
}
};
class StoneBuilder : public IBuilder
{
public:
StoneBuilder() { PRINT_FUNC; }
virtual ~StoneBuilder()
{
PRINT_FUNC;
}
virtual void BuildRoof(IHouse* house) override
{
house->BuildRoof();
}
virtual void BuildWall(IHouse* house) override
{
house->BuildWall();
}
virtual void BuildWindow(IHouse* house) override
{
house->BuildWindow();
}
virtual void BuildDoor(IHouse* house) override
{
house->BuildDoor();
}
virtual void BuildGround(IHouse* house) override
{
house->BuildGround();
}
virtual IHouse* GetHouse() override
{
return new StoneHouse;
}
};
class WoodHouse : public IHouse
{
public:
WoodHouse()
{
PRINT_FUNC;
}
virtual ~WoodHouse()
{
PRINT_FUNC;
}
virtual void BuildRoof()
{
cout << "\t生成人字形屋顶...";
PRINT_FUNC;
}
virtual void BuildWall()
{
cout << "\t生成四面围墙...";
PRINT_FUNC;
}
virtual void BuildWindow()
{
cout << "\t生成四个窗户...";
PRINT_FUNC;
}
virtual void BuildDoor()
{
cout << "\t生成两扇门...";
PRINT_FUNC;
}
virtual void BuildGround()
{
cout << "\t生成木地面...";
PRINT_FUNC;
}
};
class WoodBuilder : public IBuilder
{
public:
WoodBuilder() { PRINT_FUNC; }
virtual ~WoodBuilder()
{
PRINT_FUNC;
}
virtual void BuildRoof(IHouse* house) override
{
house->BuildRoof();
}
virtual void BuildWall(IHouse* house) override
{
house->BuildWall();
}
virtual void BuildWindow(IHouse* house) override
{
house->BuildWindow();
}
virtual void BuildDoor(IHouse* house) override
{
house->BuildDoor();
}
virtual void BuildGround(IHouse* house) override
{
house->BuildGround();
}
virtual IHouse* GetHouse() override
{
return new WoodHouse;
}
};
class Director {
public:
Director(IBuilder* builder) : m_pBuilder(builder) {}
virtual ~Director()
{
delete(m_pBuilder);
}
IHouse* Construct()
{
return m_pBuilder->CreateHouse();
}
private:
IBuilder* m_pBuilder;
};
void executeBuilder()
{
IBuilder* builder = new StoneBuilder;
Director* director = new Director(builder);
IHouse* house = director->Construct();
DELETE_PTR(director);
DELETE_PTR(house);
cout << "\n--------------------------------------" << endl;
builder = new WoodBuilder;
director = new Director(builder);
house = director->Construct();
DELETE_PTR(director);
DELETE_PTR(house);
}
}
//
/*
* 对象性能模式:单例模式,
*/
#include
mutex g_mutex;
namespace Singleton {
class LogSingleton {
public:
virtual ~LogSingleton() {
//DELETE_PTR(m_Log);
}
//采用双检查锁
static LogSingleton* GetInstance()
{
if (nullptr == m_Log)
{
g_mutex.lock();
if (nullptr == m_Log)
{
m_Log = new LogSingleton;
}
g_mutex.unlock();
}
return m_Log;
}
void printInfo(const string& str)
{
cout << str.c_str() << endl;
}
private:
LogSingleton() {}
static LogSingleton* m_Log;
};
LogSingleton* LogSingleton::m_Log = nullptr;
void executeSingleton()
{
LogSingleton::GetInstance()->printInfo("World");
LogSingleton::GetInstance()->printInfo(",");
LogSingleton::GetInstance()->printInfo("Hello");
LogSingleton::GetInstance()->printInfo("!");
}
}
//
/*
* 对象性能模式:享元模式,
*/
#include
//
/*
* 接口隔离模式:门面模式,作为一种架构设计模式,为子系统中的一组接口(耦合关系比较大的一系列组件)提供了一个一致(稳定)的界面,Facade模式定义了一个高层接口,使得子系统更加容易使用(复用)
*/
namespace Facade {
class SubSystemOne {
public:
void MethodOne() { PRINT_FUNC; }
};
class SubSystemTwo {
public:
void MethodTwo() { PRINT_FUNC; }
};
class SubSystemThree {
public:
void MethodThree() { PRINT_FUNC; }
};
class SubSystemFour {
public:
void MethodFour() { PRINT_FUNC; }
};
class SubSystemFive {
public:
void MethoFive() { PRINT_FUNC; }
};
class Facade {
public:
void Method1()
{
m_SubSys1.MethodOne();
m_SubSys2.MethodTwo();
m_SubSys5.MethoFive();
}
void Method2()
{
m_SubSys1.MethodOne();
m_SubSys2.MethodTwo();
m_SubSys3.MethodThree();
m_SubSys4.MethodFour();
m_SubSys5.MethoFive();
}
private:
SubSystemOne m_SubSys1;
SubSystemTwo m_SubSys2;
SubSystemThree m_SubSys3;
SubSystemFour m_SubSys4;
SubSystemFive m_SubSys5;
};
void executeFacade()
{
Facade* facade = new Facade;
facade->Method1();
facade->Method2();
DELETE_PTR(facade);
}
}
//
/*
* 接口隔离模式:代理模式,某些对象由于某些原因,如果直接访问会给使用者或者系统带来麻烦;
* 代理类和具体目标类,同时继承抽象目标类,这样可以保证某些接口的一致性
*/
namespace Proxy {
class Subject
{
public:
virtual void Operation() = 0;
};
//真实目标A
class RealSubjectA : public Subject{
public:
virtual void Operation()
{
PRINT_FUNC;
}
};
//真实目标B
class RealSubjectB : public Subject {
public:
virtual void Operation()
{
PRINT_FUNC;
}
};
//代理A,可以访问具体目标类A
class ProxyA : public Subject {
public:
ProxyA()
{
m_pRealSubject = new RealSubjectA;
}
virtual ~ProxyA()
{
DELETE_PTR(m_pRealSubject);
}
virtual void Operation()
{
m_pRealSubject->Operation();
}
private:
Subject* m_pRealSubject;
};
//代理B,可以访问具体目标类B
class ProxyB : public Subject {
public:
ProxyB()
{
m_pRealSubject = new RealSubjectB;
}
virtual ~ProxyB()
{
DELETE_PTR(m_pRealSubject);
}
virtual void Operation()
{
m_pRealSubject->Operation();
}
private:
Subject* m_pRealSubject;
};
void executeProxy()
{
Subject* proxy = new ProxyA();
proxy->Operation();
proxy = new ProxyB();
proxy->Operation();
}
}
//
/*
* 接口隔离模式:适配器模式,
*/
namespace Adapter {
class Target {//目标
public:
virtual void Request() = 0;
};
class Adaptee {//被适配者
public:
void SpecificRequest()
{
PRINT_INFO("执行特殊请求...");
}
};
class Adapter : public Target{//适配器和被适配器的对应关系明确的
public:
Adapter()
{
m_pAdaptee = new Adaptee;//紧耦合
}
virtual ~Adapter()
{
DELETE_PTR(m_pAdaptee);
}
void Request() override
{
PRINT_INFO("1.使用对象适配器...");
m_pAdaptee->SpecificRequest();
}
private:
Adaptee* m_pAdaptee;//看得出Adapter是对象适配器
};
class ClassAdapter : public Target,public Adaptee {//看得出Adapter是类适配器(不推荐),适配器和被适配器的对应关系明确的
public:
void Request() override
{
PRINT_INFO("2.使用类适配器...");
this->SpecificRequest();
}
private:
Adaptee* m_pAdaptee;//看得出Adapter是对象适配器
};
void executeAdapter()
{
Target* adapter = new Adapter();
adapter->Request();
adapter = new ClassAdapter();
adapter->Request();
delete adapter;
}
}
//
/*
* 接口隔离模式:中介者模式,用一个中介对象来封装一系列对象的交互,是的各个对象不需要显示相互引用,使其耦合松散,独立
*/
namespace Mediator {
class Colleague;
class IMediator {
public:
virtual void SendMsg(const string& msg,Colleague* colleague) = 0;
};
class Colleague {
public:
Colleague(IMediator* mediator) : m_pMediator(mediator){}
virtual void ReceiveMsg(const string& msg) = 0;
virtual void SendMsg(const string& msg) = 0;
protected:
IMediator* m_pMediator;
};
class ConcreteColleague1 : public Colleague {
public:
ConcreteColleague1(IMediator* mediator) : Colleague(mediator)
{
}
virtual void ReceiveMsg(const string& msg)
{
string sMsg = "同事1:收到信息,";
sMsg.append(msg);
PRINT_INFO(sMsg.c_str());
}
virtual void SendMsg(const string& msg)
{
m_pMediator->SendMsg(msg,this);
}
};
class ConcreteColleague2 : public Colleague {
public:
ConcreteColleague2(IMediator* mediator) : Colleague(mediator)
{
}
virtual void ReceiveMsg(const string& msg)
{
string sMsg = "同事2:收到信息,";
sMsg.append(msg);
PRINT_INFO(sMsg.c_str());
}
virtual void SendMsg(const string& msg)
{
m_pMediator->SendMsg(msg, this);
}
};
class ConcreteMediator : public IMediator {
public:
void SetColleague1(ConcreteColleague1* colleague)
{
m_pColleague1 = colleague;
}
void SetColleague2(ConcreteColleague2* colleague)
{
m_pColleague2 = colleague;
}
virtual void SendMsg(const string& msg, Colleague* colleague) override
{
if (m_pColleague1 == colleague)
{
m_pColleague2->ReceiveMsg(msg);
}
else if (m_pColleague2 == colleague)
{
m_pColleague1->ReceiveMsg(msg);
}
}
private:
ConcreteColleague1* m_pColleague1;
ConcreteColleague2* m_pColleague2;
};
void executeMediator()
{
ConcreteMediator* mediator = new ConcreteMediator;
ConcreteColleague1* colleague1 = new ConcreteColleague1(mediator);
ConcreteColleague2* colleague2 = new ConcreteColleague2(mediator);
mediator->SetColleague1(colleague1);
mediator->SetColleague2(colleague2);
colleague1->SendMsg("我好饿...");
colleague2->SendMsg("我现在还好,待会去吃饭...");
}
}
//
/*
* 状态变化模式:状态模式,
*/
namespace State {
//enum LightState
//{
// ON,
// OFF
//};
class Context;
class IState {
public:
virtual ~IState()
{
PRINT_FUNC;
}
virtual void Handle(Context* context) = 0;
};
class Context {
public:
/*Context(IState* state) : m_pState(state) {}
Context(IState* state) : m_pState(state){}*/
virtual ~Context() {
PRINT_FUNC;
DELETE_PTR(m_pState);
}
void SetState(IState* state)
{
DELETE_PTR(m_pState);
m_pState = state;
}
virtual void Request()
{
m_pState->Handle(this);
}
private:
IState* m_pState;
};
class ONState;
class OFFState : public IState {
public:
~OFFState() {
PRINT_FUNC;
}
virtual void Handle(Context* context) override;
};
class ONState : public IState {
public:
~ONState() {
PRINT_FUNC;
}
virtual void Handle(Context* context) override;
};
void OFFState::Handle(Context* context)
{
PRINT_INFO("天亮了,把灯关闭");
IState* state = new ONState;
context->SetState(state);//状态切换:从OFF切到ON
}
void ONState::Handle(Context* context)
{
PRINT_INFO("晚上了,把灯打开");
IState* state = new OFFState;
context->SetState(state);//状态切换:从ON切到OFF
}
void executeState()
{
Context* context = new Context;
IState* state = new ONState;
context->SetState(state);
context->Request();
context->Request();
context->Request();
context->Request();
delete context;
}
}
//
/*
* 状态变化模式:备忘录模式,在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将对象恢复到原先保存的状态
*/
namespace Memento {
class Memento {
public:
Memento(const string& state)
{
m_State = state;
}
virtual ~Memento()
{
PRINT_FUNC;
}
void SetState(const string& state)
{
m_State = state;
}
string GetState() const
{
return m_State;
}
private:
string m_State;
};
class Caretaker {
public:
Caretaker(Memento* m) : m_Memento(m){}
virtual ~Caretaker()
{
PRINT_FUNC;
DELETE_PTR(m_Memento);
}
Memento* GetMemento()
{
return m_Memento;
}
private:
Memento* m_Memento;
};
class Originator {
public:
Originator():m_State("Empty State")
{
}
virtual ~Originator()
{
PRINT_FUNC;
}
void SetState(const string& state)
{
m_State = state;
}
void PrintState()
{
PRINT_INFO(m_State.c_str());
}
void SetMemento(const Memento& m)
{
m_State = m.GetState();
}
Memento* CreateMemento()
{
return new Memento(m_State);
}
private:
string m_State;
};
void executeMemento()
{
//原发器
Originator* originator = new Originator;
originator->SetState("state01");
originator->PrintState();
//实例化管理者,创建一个备忘录存储在管理者中
Caretaker* c = new Caretaker(originator->CreateMemento());
//更改原发器的状态名称
originator->SetState("state02");
originator->PrintState();
originator->SetMemento(*(c->GetMemento()));
originator->PrintState();
delete c;
delete originator;
}
}
//
/*
* 数据结构模式:组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构。
* 安全组合模式,就是Composite和Leaf具有不同的接口,考虑到Leaf作为叶子结点不需要Add、Remove、GetChild
*/
#include
namespace Component {
class Component {
public:
Component(const string& tag): m_sTag(tag)
{
}
virtual void Operation() = 0;
protected:
string m_sTag;
};
class Composite : public Component {
public:
Composite(const string& tag) : Component(tag)
{
}
virtual void Operation()
{
PRINT_INFO(m_sTag.c_str());
PRINT_FUNC;
for (auto iter = m_listComp.begin() ; iter != m_listComp.end(); ++iter)
{
(*iter)->Operation();
}
}
virtual void Add(Component* comp)
{
m_listComp.push_back(comp);
}
virtual void Remove(Component* comp)
{
auto iter = find(m_listComp.begin(), m_listComp.end(), comp);
m_listComp.erase(iter);
}
virtual Component* GetChild(const int& i)
{
Component* comp = m_listComp.at(i);
return comp;
}
private:
vector m_listComp;
};
class Leaf : public Component {
public:
Leaf(const string& tag) : Component(tag)
{
}
virtual void Operation() override
{
PRINT_INFO(m_sTag.c_str());
PRINT_FUNC;
}
};
void executeComponent()
{
Composite* root = new Composite("Root");
Composite*leftComp = new Composite("LeftComp");
Composite*RightComp = new Composite("RightComp");
Component* leftLeaf1 = new Leaf("leftLeaf1");
Component* leftLeaf2 = new Leaf("leftLeaf2");
Component* leftLeaf3 = new Leaf("leftLeaf3");
root->Add(leftComp);
root->Add(RightComp);
leftComp->Add(leftLeaf1);
leftComp->Add(leftLeaf2);
leftComp->Add(leftLeaf3);
root->Operation();
}
}
//
/*
* 数据结构模式:迭代器模式,
*/
namespace Iterator {
void executeIterator()
{
}
}
//
/*
* 数据结构模式:职责链模式,
*/
namespace ChainOfResponsibility {
class Handler {
public:
Handler(Handler* successor = nullptr):m_pSuccessor(successor)
{
}
virtual ~Handler() { DELETE_PTR(m_pSuccessor); }
virtual void HandlerRequest() = 0;
protected:
Handler* m_pSuccessor;
};
class ConcreteHandler1 : public Handler
{
public:
ConcreteHandler1(Handler* successor = nullptr) : Handler(successor)
{
}
virtual void HandlerRequest()
{
if (nullptr != m_pSuccessor)
{
m_pSuccessor->HandlerRequest();
}
else {
PRINT_INFO("ConcreteHandler1::HandlerRequest");
}
}
};
class ConcreteHandler2 : public Handler
{
public:
ConcreteHandler2(Handler* successor = nullptr) : Handler(successor)
{
}
virtual void HandlerRequest()
{
if (nullptr != m_pSuccessor)
{
m_pSuccessor->HandlerRequest();
}
else {
PRINT_INFO("ConcreteHandler2::HandlerRequest");
}
}
};
void executeChainOfResponsibility()
{
Handler* handler1 = new ConcreteHandler1;
Handler* handler2 = new ConcreteHandler2(handler1);
handler2->HandlerRequest();
}
}
看到另一个博主写的关于李建忠老师讲的设计模式笔记,总结的还是很详细的,点赞
李建忠讲23种设计模式笔记-上_0萌萌哒0的博客-CSDN博客
李建忠讲23种设计模式笔记-下_0萌萌哒0的博客-CSDN博客_李建忠 设计模式