以下代码来源: 设计模式精解-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; }
原文地址:https://www.cnblogs.com/fourmi/p/12076845.html
时间: 2024-11-29 04:09:16