Skip to content

Instantly share code, notes, and snippets.

@masaki-shimura
Created June 21, 2021 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaki-shimura/e388363645e7056d30d347f8ce29f27d to your computer and use it in GitHub Desktop.
Save masaki-shimura/e388363645e7056d30d347f8ce29f27d to your computer and use it in GitHub Desktop.
【デザインパターン】ブリッジパターン
/*
ブリッジパターン のサンプルプログラム
説明
「橋渡し」のクラスを用意することによって、クラスを複数の方向に拡張させることを目的とする。
*/
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class TextImp
{
public:
string getString()
{
stringstream ss;
for( int i = 0 ; i < m_rows.size() ; i++ )
{
if(i != 0)
{
ss << "\n";
}
ss << m_rows[i];
}
return ss.str();
}
virtual void appendLine(string value) = 0;
protected:
vector<string> m_rows ={};
};
// -------------------------------------------
// 構築用
// -------------------------------------------
class TextBuilder : public TextImp
{
public:
void appendLine(string value)
{
m_rows.push_back(value);
}
};
class HtmlBuilder : public TextImp
{
public:
void appendLine(string value)
{
m_rows.push_back("<span>"+value+"</span><br/>");
}
};
// -------------------------------------------
// 処理用
// -------------------------------------------
class IText
{
public:
TextImp* m_textImp;
private:
virtual string getText() = 0;
virtual void addLine(string value) = 0;
};
class TextMaker: IText
{
public:
TextMaker( TextImp* _textImp )
{
this->m_textImp = _textImp;
}
string getText()
{
return m_textImp->getString();
}
void addLine(string _value)
{
m_textImp->appendLine(_value);
}
};
//構築用関数
TextMaker fillTextBuilder( TextImp* _textImp )
{
TextMaker textMaker(_textImp);
textMaker.addLine("test A");
textMaker.addLine("test B");
return textMaker;
}
int main(void){
// 通常テキスト
TextBuilder _textBuilder;
TextMaker _textMaker = fillTextBuilder(&_textBuilder);
string text = _textMaker.getText();
cout << text;
// HTML テキスト
HtmlBuilder _htmlBuilder;
TextMaker _htmlMaker = fillTextBuilder(&_htmlBuilder);
string _textHtml = _htmlMaker.getText();
cout << + "\n"+_textHtml;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment