当前位置:   article > 正文

桥接模式C++实现

桥接模式c++实现

1. 理解总结

桥接模式是一种结构型设计模式, 可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构, 从而能在开发时分别使用。

代理模式是一个类与另一个类的组合,桥接模式是一组类和另外一组类的组合

2. 编码实现

资料参考

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. /**
  4. * 实现类的接口
  5. */
  6. class Implementation {
  7. public:
  8. virtual ~Implementation() {}
  9. virtual string OperationImplementation() const = 0;
  10. };
  11. /**
  12. * 具体实现类1
  13. */
  14. class ConcreteImplementationA : public Implementation {
  15. public:
  16. string OperationImplementation() const override {
  17. return "ConcreteImplementationA: Here's the result on the platform A.\n";
  18. }
  19. };
  20. /**
  21. * 具体实现类2
  22. */
  23. class ConcreteImplementationB : public Implementation {
  24. public:
  25. string OperationImplementation() const override {
  26. return "ConcreteImplementationB: Here's the result on the platform B.\n";
  27. }
  28. };
  29. /**
  30. * 有点类似抽象类接口,但是它同时组合了抽象类
  31. */
  32. class Abstraction {
  33. protected:
  34. Implementation* implementation_;
  35. public:
  36. Abstraction(Implementation* implementation) : implementation_(implementation) {
  37. }
  38. virtual ~Abstraction() {
  39. }
  40. virtual string Operation() const {
  41. return "Abstraction: Base operation with:\n" + implementation_->OperationImplementation();
  42. }
  43. };
  44. /**
  45. * 扩展抽象类
  46. */
  47. class ExtendedAbstraction : public Abstraction {
  48. public:
  49. ExtendedAbstraction(Implementation* implementation) : Abstraction(implementation){
  50. }
  51. string Operation() const override {
  52. return "ExtendedAbstraction: Extended operation with:\n" + implementation_->OperationImplementation();
  53. }
  54. };
  55. void ClientCode(const Abstraction &abstraction) {
  56. cout << abstraction.Operation();
  57. }
  58. int main() {
  59. Implementation *implementation = new ConcreteImplementationA;
  60. Abstraction *abstraction = new Abstraction(implementation);
  61. ClientCode(*abstraction);
  62. cout << endl;
  63. delete implementation;
  64. delete abstraction;
  65. implementation = new ConcreteImplementationB;
  66. abstraction = new ExtendedAbstraction(implementation);
  67. ClientCode(*abstraction);
  68. delete implementation;
  69. delete abstraction;
  70. return 0;
  71. }

输出结果:

  1. Abstraction: Base operation with:
  2. ConcreteImplementationA: Here's the result on the platform A.
  3. ExtendedAbstraction: Extended operation with:
  4. ConcreteImplementationB: Here's the result on the platform B.

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号