设计模式-Bridge(结构型模式)-用于客户需求较多,频繁对类进行添加修改的情形,将抽象类与具体实现类分开
Posted fourmi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-Bridge(结构型模式)-用于客户需求较多,频繁对类进行添加修改的情形,将抽象类与具体实现类分开相关的知识,希望对你有一定的参考价值。
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//AbstractionImp.h
#pragma once class AbstractionImp { public: virtual ~AbstractionImp(); virtual void Operation() = 0; protected: AbstractionImp(); private: }; class ConcreateAbstractionImpA :public AbstractionImp { public: ConcreateAbstractionImpA(); ~ConcreateAbstractionImpA(); virtual void Operation(); protected: private: }; class ConcreateAbstractionImpB :public AbstractionImp { public: ConcreateAbstractionImpB(); ~ConcreateAbstractionImpB(); virtual void Operation(); protected: private: };
//Abstraction.cpp
#include"AbstractionImp.h" #include<iostream> AbstractionImp::AbstractionImp(){} AbstractionImp::~AbstractionImp(){} void AbstractionImp::Operation() { std::cout << "AbstractionImp..." << std::endl; } ConcreateAbstractionImpA::ConcreateAbstractionImpA(){} ConcreateAbstractionImpA::~ConcreateAbstractionImpA(){} void ConcreateAbstractionImpA::Operation() { std::cout << "ConcreateAbstractionImpA..." << std::endl; } ConcreateAbstractionImpB::ConcreateAbstractionImpB(){} ConcreateAbstractionImpB::~ConcreateAbstractionImpB(){} void ConcreateAbstractionImpB::Operation() { std::cout << "ConcreateAbstractionImpB..." << std::endl; }
//Abstraction.h
#pragma once class AbstractionImp; class Abstraction { public: virtual ~Abstraction(); virtual void Operation() = 0; protected: Abstraction(); private: }; class RefinedAbstraction :public Abstraction { public: RefinedAbstraction(AbstractionImp* imp); ~RefinedAbstraction(); void Operation(); protected: private: AbstractionImp* _imp; };
//Abstraction.cpp
#include"Abstraction.h" #include"AbstractionImp.h" #include<iostream> Abstraction::Abstraction(){} Abstraction::~Abstraction(){} RefinedAbstraction::RefinedAbstraction(AbstractionImp* imp) { _imp = imp; } RefinedAbstraction::~RefinedAbstraction(){} void RefinedAbstraction::Operation() { _imp->Operation(); }
//main.cpp
#include"Abstraction.h" #include"AbstractionImp.h" #include<string> int main(int args, char* argv) { AbstractionImp* impA = new ConcreateAbstractionImpA(); Abstraction* abs = new RefinedAbstraction(impA); abs->Operation(); AbstractionImp* impB = new ConcreateAbstractionImpB(); Abstraction* abs1 = new RefinedAbstraction(impB); abs1->Operation(); getchar(); return 0; }
以上是关于设计模式-Bridge(结构型模式)-用于客户需求较多,频繁对类进行添加修改的情形,将抽象类与具体实现类分开的主要内容,如果未能解决你的问题,请参考以下文章