Bridge (実装側と機能追加側との橋渡し)

#include <iostream>
#include <time.h>
using namespace std;
 
// 実装クラス
class SortImple {
public:
	virtual void sort() = 0;
};
 
class QuickSortImple : public SortImple {
public:
	virtual void sort() {
		cout << "quick sorting..." << endl;
		cout << "finish." << endl;
	}
};
 
class BubbleSortImple : public SortImple {
public:
	virtual void sort() {
		cout << "bubble sorting..." << endl;
		cout << "finish." << endl;
	}
};
 
 
// 機能追加側
class Sorter {
public:
	Sorter(SortImple *sort) {
		m_sort = sort;
	}
	virtual void sort() {
		m_sort->sort();
	}
private:
	SortImple *m_sort;
};
 
// 時間計測を追加した
class TimerSorter : public Sorter {
public:
	TimerSorter(SortImple *sort) : Sorter(sort) { }
	virtual void sort() {
		clock_t start, end;
		start = clock();
		Sorter::sort();
		end = clock();
		cout << "time: " << (int)(end - start) << endl;
	}
};
 
 
int main(int argc, char **argv) {
	SortImple *sort;
	if (argc == 1) {
		sort = new QuickSortImple;
	} else {
		sort = new BubbleSortImple;
	}
	Sorter *sorter = new TimerSorter(sort);
	sorter->sort();
	delete sort;
	delete sorter;
	return 0;
}
 



参考サイト

デザインパターンを“喩え話”で分かり易く理解する
http://www.netlaputa.ne.jp/~hijk/study/oo/designpattern.html



デザインパターンの骸骨たち
http://www002.upp.so-net.ne.jp/ys_oota/mdp/
最終更新:2011年11月14日 00:17