设计模式C++实现(10)——桥接模式

来源:互联网 发布:手机淘宝店标怎么设置 编辑:程序博客网 时间:2024/05/16 04:42

 [DP]书上定义:将抽象部分与它的实现部分分离,使它们都可以独立地变化。考虑装操作系统,有多种配置的计算机,同样也有多款操作系统。如何运用桥接模式呢?可以将操作系统和计算机分别抽象出来,让它们各自发展,减少它们的耦合度。当然了,两者之间有标准的接口。这样设计,不论是对于计算机,还是操作系统都是非常有利的。下面给出这种设计的UML图,其实就是桥接模式的UML图。

         给出C++的一种实现:

[cpp] view plain copy
 print?
  1. //操作系统  
  2. class OS  
  3. {  
  4. public:  
  5.     virtual void InstallOS_Imp() {}  
  6. };  
  7. class WindowOS: public OS  
  8. {  
  9. public:  
  10.     void InstallOS_Imp() { cout<<"安装Window操作系统"<<endl; }   
  11. };  
  12. class LinuxOS: public OS  
  13. {  
  14. public:  
  15.     void InstallOS_Imp() { cout<<"安装Linux操作系统"<<endl; }   
  16. };  
  17. class UnixOS: public OS  
  18. {  
  19. public:  
  20.     void InstallOS_Imp() { cout<<"安装Unix操作系统"<<endl; }   
  21. };  
  22. //计算机  
  23. class Computer  
  24. {  
  25. public:  
  26.     virtual void InstallOS(OS *os) {}  
  27. };  
  28. class DellComputer: public Computer  
  29. {  
  30. public:  
  31.     void InstallOS(OS *os) { os->InstallOS_Imp(); }  
  32. };  
  33. class AppleComputer: public Computer  
  34. {  
  35. public:  
  36.     void InstallOS(OS *os) { os->InstallOS_Imp(); }  
  37. };  
  38. class HPComputer: public Computer  
  39. {  
  40. public:  
  41.     void InstallOS(OS *os) { os->InstallOS_Imp(); }  
  42. };  

        客户使用方式:

[css] view plain copy
 print?
  1. int main()  
  2. {  
  3.     OS *os1 = new WindowOS();  
  4.     OS *os2 = new LinuxOS();  
  5.     Computer *computer1 = new AppleComputer();  
  6.     computer1->InstallOS(os1);  
  7.     computer1->InstallOS(os2); 
  8. delete os1;
  9. delete os2;
  10. delete computer1;
  11. return 0;

  12. }  
1 0
原创粉丝点击