1. 程式人生 > >《設計模式》學習筆記——橋接模式

《設計模式》學習筆記——橋接模式

Bridge Pattern被稱之為橋接模式,屬於構造型模式。Bridge Pattern基於類的最小設計原則,通過使用封裝、聚和以及繼承等行為來讓不同的類承擔不同的責任。它的主要特點是把抽象類與行為實現分離開來,從而可以保持各個部分的獨立性以及對應它們的功能擴充套件 。

Brige.h

#pragma once
#include<iostream>
#include<string>

// 抽象介面
class Engine
{
public:
	virtual void InstallEngine() = 0;
private:
protected:
};

// 具體引擎類
class Engine4400CC:public Engine
{
public:
	virtual void InstallEngine()
	{
		std::cout << "Install Engine4400CC" << std::endl;
	}
private:
protected:
};

// 具體引擎類
class Engine4500CC :public Engine
{
public:
	virtual void InstallEngine()
	{
		std::cout << "Install Engine4500CC" << std::endl;
	}
private:
protected:
};

// 抽象介面
class Car
{
public:
	Car(Engine * engine):m_engine(engine){}
	virtual~Car() { delete m_engine; }
	virtual void InstallEngine() = 0;
private:
	
protected:
	Engine * m_engine;
};

// 具體實現類
class WBM5:public Car
{
public:
	WBM5(Engine * engine) :Car(engine) {}
	virtual~WBM5() { }

	virtual void InstallEngine()
	{
		m_engine->InstallEngine();
	}
private:
protected:
};


// 具體實現類
class WBM6 :public Car
{
public:
	WBM6(Engine * engine) :Car(engine) {}
	virtual ~WBM6() {  }

	virtual void InstallEngine()
	{
		m_engine->InstallEngine();
	}
private:
protected:
};



class Brige
{
public:
	Brige() {};
	~Brige() {};
};

Brige.cpp

#include "Brige.h"

mainTest.cpp

#include<iostream>
#include"Brige.h"

int main(void)
{
	Engine* engine = new Engine4400CC;
	WBM6* wbm6 = new WBM6(engine);
	wbm6->InstallEngine();
	delete wbm6;

	wbm6= new WBM6(new Engine4500CC);
	wbm6->InstallEngine();
	delete wbm6;
	system("pause");
	return 0;
}