二十三种设计模式(一)的简单实现之桥接模式(Bridge Pattern)

桥接模式主要描述了类的功能层次结构和类的实现层次的分离,其中主要体现了一个委托的概念。

废话不多说,直接放代码了。

1、首先是类的功能层次

 1 #pragma once
 2 #include "DisplayImpl.h"
 3 class CDisplay
 4 {
 5 public:
 6     CDisplay(CDisplayImpl* pDisplayImpl);
 7     CDisplay();
 8     virtual ~CDisplay();
 9 
10     void Display();
11 
12 private:
13     CDisplayImpl* m_pDisplayImpl;
14 };
 1 #include "Display.h"
 2 #include <Windows.h>
 3 
 4 CDisplay::CDisplay(CDisplayImpl* pDisplayImpl)
 5 {
 6     m_pDisplayImpl = pDisplayImpl;
 7 }
 8 
 9 
10 CDisplay::CDisplay()
11 {
12 
13 }
14 
15 CDisplay::~CDisplay()
16 {
17 }
18 
19 void CDisplay::Display()
20 {
21     if (NULL != m_pDisplayImpl)
22     {
23         m_pDisplayImpl->Display();
24     }
25 }
 1 #pragma once
 2 #include "Display.h"
 3 class CCountDisplay :
 4     public CDisplay
 5 {
 6 public:
 7     CCountDisplay(CDisplayImpl* pDisplayImpl);
 8     virtual ~CCountDisplay();
 9 
10     void MultiDisplay(int nTimes);
11 };
 1 #include "CountDisplay.h"
 2 
 3 
 4 CCountDisplay::CCountDisplay(CDisplayImpl* pDisplayImpl)
 5 {
 6     CDisplay::CDisplay(pDisplayImpl);
 7 }
 8 
 9 CCountDisplay::~CCountDisplay()
10 {
11 }
12 
13 void CCountDisplay::MultiDisplay(int nTimes)
14 {
15     for (int nIndex = 0; nIndex < nTimes; nIndex++)
16     {
17         CDisplay::Display();
18     }
19 }

接下来是类的实现层次:

接口类:

1 #pragma once
2 class CDisplayImpl
3 {
4 public:
5     virtual void Display() = 0;
6 };
 1 #pragma once
 2 #include "DisplayImpl.h"
 3 #include <string>
 4 
 5 class CStringDisplayImpl :
 6     public CDisplayImpl
 7 {
 8 public:
 9     CStringDisplayImpl(std::string strContent);
10     virtual ~CStringDisplayImpl();
11 
12     virtual void Display();
13 
14 private:
15     std::string m_strContent;
16 };
 1 #include "StringDisplayImpl.h"
 2 #include <iostream>
 3 
 4 CStringDisplayImpl::CStringDisplayImpl(std::string strContent)
 5 {
 6     m_strContent = strContent;
 7 }
 8 
 9 
10 CStringDisplayImpl::~CStringDisplayImpl()
11 {
12 }
13 
14 void CStringDisplayImpl::Display()
15 {
16     std::cout << m_strContent << std::endl;
17 }

最后是用户的使用:

 1 #include "CountDisplay.h"
 2 #include "StringDisplayImpl.h"
 3 #include <windows.h>
 4 
 5 int main()
 6 {
 7     CDisplayImpl* pDisplay = new CStringDisplayImpl("Hello Design Pattern! ");
 8     CDisplay display = CDisplay(pDisplay);
 9     display.Display();
10     CCountDisplay countDisplay = CCountDisplay(pDisplay);
11     countDisplay.MultiDisplay(5);
12     system("pause");
13     return 0;
14 }

 

在这里,遇到的问题在于countDisplay对象中具体实现成员的指针为空,但经过调试明明已经进行了赋值,希望有大佬可以提出问题的所在。

posted @ 2019-03-31 22:10  Li_Quid  阅读(140)  评论(0编辑  收藏  举报