赞
踩
桥接模式是一种结构型设计模式, 可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构, 从而能在开发时分别使用。
代理模式是一个类与另一个类的组合,桥接模式是一组类和另外一组类的组合
- #include <bits/stdc++.h>
- using namespace std;
-
- /**
- * 实现类的接口
- */
- class Implementation {
- public:
- virtual ~Implementation() {}
- virtual string OperationImplementation() const = 0;
- };
-
- /**
- * 具体实现类1
- */
- class ConcreteImplementationA : public Implementation {
- public:
- string OperationImplementation() const override {
- return "ConcreteImplementationA: Here's the result on the platform A.\n";
- }
- };
-
- /**
- * 具体实现类2
- */
- class ConcreteImplementationB : public Implementation {
- public:
- string OperationImplementation() const override {
- return "ConcreteImplementationB: Here's the result on the platform B.\n";
- }
- };
-
- /**
- * 有点类似抽象类接口,但是它同时组合了抽象类
- */
- class Abstraction {
- protected:
- Implementation* implementation_;
-
- public:
- Abstraction(Implementation* implementation) : implementation_(implementation) {
- }
-
- virtual ~Abstraction() {
- }
-
- virtual string Operation() const {
- return "Abstraction: Base operation with:\n" + implementation_->OperationImplementation();
- }
- };
-
- /**
- * 扩展抽象类
- */
- class ExtendedAbstraction : public Abstraction {
- public:
- ExtendedAbstraction(Implementation* implementation) : Abstraction(implementation){
- }
-
- string Operation() const override {
- return "ExtendedAbstraction: Extended operation with:\n" + implementation_->OperationImplementation();
- }
- };
-
- void ClientCode(const Abstraction &abstraction) {
- cout << abstraction.Operation();
- }
- int main() {
- Implementation *implementation = new ConcreteImplementationA;
- Abstraction *abstraction = new Abstraction(implementation);
- ClientCode(*abstraction);
- cout << endl;
- delete implementation;
- delete abstraction;
-
- implementation = new ConcreteImplementationB;
- abstraction = new ExtendedAbstraction(implementation);
- ClientCode(*abstraction);
- delete implementation;
- delete abstraction;
-
- return 0;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
输出结果:
- Abstraction: Base operation with:
- ConcreteImplementationA: Here's the result on the platform A.
- ExtendedAbstraction: Extended operation with:
- ConcreteImplementationB: Here's the result on the platform B.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。