我所理解的設計模式(C++實現)——橋模式(Bridge Pattern)

來源:互聯網
上載者:User

橋模式,其作用就是讓抽象與實現相分離,讓兩者都能夠各自變化。

舉例來說吧,畫圖,我可以畫矩形,圓,三角形等等,在哪裡畫呢?我可以在pdf上畫,也可以在doc上面畫。畫什麼圖和在哪裡畫都是可以獨立變化的,此種情況就比較適合用橋模式。就是說設計中有超過一維的變化我們就可以用橋模式。如果只有一維在變化,那麼我們用繼承就可以圓滿的解決問題。

 

我的圖形定義: 

#pragma once#include<vector>#include"ImpShape.h"class IShape{public:IShape(void);virtual ~IShape(void);virtual std::vector<Point> getDrawPoints();void paint();public:ImpShape *implementor;};

其他圖形都繼承之:

#pragma once#include "ishape.h"class CRectangle :public IShape{public:CRectangle(void);~CRectangle(void);};#pragma once#include "ishape.h"class CCircle :public IShape{public:CCircle(void);~CCircle(void);};

那麼在怎麼畫這個問題上,該怎麼實現呢?我先定義一個shape的實作類別:

#pragma once#include<vector>class ImpShape{public:ImpShape(void);virtual ~ImpShape(void);public:virtual void draw(std::vector<Point>&);};

那麼讓pdf和doc的實作類別都繼承自ImpShape:

#pragma once#include "impshape.h"class ImpPdf :public ImpShape{public:ImpPdf(void);~ImpPdf(void);};#pragma once#include "impshape.h"class ImpDoc :public ImpShape{public:ImpDoc(void);~ImpDoc(void);};

那ImpPdf和ImpDoc必須繼承且重寫ImpShape的draw函數。

 

我們的抽象和實現都分別實現好了,那兩者如何聯絡,如何使用的?

  • 關於聯絡,細心的你也許已經發現,IShape裡麵包含一個ImpShape的指標,包含!對。因為ImpShape是實現IShape的,這裡用包含,我們可以在IShape的其他函數裡方便的調用。
#include "StdAfx.h"#include "IShape.h"IShape::IShape(void){}IShape::~IShape(void){}void IShape::paint(){std::vector<Point> vpoints = getDrawPoints();this->implementor->draw(vpoints);}
  • 關於使用,很簡單:
IShape *item = new CCircle();item->implementor = new ImpPdf();item->paint();item = new CRectangle();item->implementor = new ImpDoc();item->paint();

 

這樣既滿足了畫什麼圖形的變化,也滿足了在什麼上畫的問題,他們之間的類圖如下:

 

LCL_data原創於CSDN.Net[http://blog.csdn.net/lcl_data/article/details/8710134]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.