Skip to content

Instantly share code, notes, and snippets.

@masaki-shimura
Last active June 15, 2021 05:12
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/9cc80504fcec01f95f06aed54a88f7e7 to your computer and use it in GitHub Desktop.
Save masaki-shimura/9cc80504fcec01f95f06aed54a88f7e7 to your computer and use it in GitHub Desktop.
【デザインパターン 復習】ビルダー
/*
ビルダークラス のサンプルプログラム
説明
構築用クラスを分離することで 出力結果を変える事を用意にするデザインパターン
ポイント
・データ構築用の抽象クラス の作成
・それを継承させて 仕様にあわせた データ構築クラス の作成
・データを設定しておくようの Make クラスの作成
・Make クラスに 仕様に合わせた構築用クラスを渡すことで自動的に処理の切り替え
*/
#include <iostream>
#include <string>
using namespace std;
// Abstract Builder
// 構築用クラスのインターフェース
// データ構築に必要なメソッドを定義しておく
class ITextBuilder
{
public:
virtual void addText(string _text) = 0;
virtual void addTextLine(string _text) = 0;
};
// ConcreteBuilder
// 文字情報を加工するためのクラス
class TextBuilder : public ITextBuilder
{
public:
void addText(string _text)
{
m_text += _text;
}
void addTextLine(string _text)
{
m_text += "\n" + _text;
}
string getText()
{
return m_text;
}
private:
string m_text;
};
// テキストをHTMLベースで書き換える
class HtmlBuilder : public ITextBuilder
{
public:
void addText(string _text)
{
m_text += "<span>" + _text + "</span>";
}
void addTextLine(string _text)
{
m_text += "<br/>\n";
addText(_text);
}
string getText()
{
return m_text;
}
private:
string m_text;
};
// Director
// 構築クラスでデータを生成する
class TextMaker
{
public:
//固定文字列情報を出力する
void makeText(ITextBuilder* _textBuilder)
{
_textBuilder->addText("sample text 1");
_textBuilder->addTextLine("sample text 2");
}
};
int main(void){
TextMaker textMaker;
//通常のテキストで処理
// テキスト構築用オブジェクトを生成した後、結果を出力する
TextBuilder textBuilder;
textMaker.makeText(&textBuilder);
cout << "出力結果\n" << textBuilder.getText() + "\n";
HtmlBuilder htmlBuilder;
textMaker.makeText(&htmlBuilder);
cout << "出力結果\n" << htmlBuilder.getText() + "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment