Last active
June 15, 2021 05:12
-
-
Save masaki-shimura/9cc80504fcec01f95f06aed54a88f7e7 to your computer and use it in GitHub Desktop.
【デザインパターン 復習】ビルダー
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ビルダークラス のサンプルプログラム | |
説明 | |
構築用クラスを分離することで 出力結果を変える事を用意にするデザインパターン | |
ポイント | |
・データ構築用の抽象クラス の作成 | |
・それを継承させて 仕様にあわせた データ構築クラス の作成 | |
・データを設定しておくようの 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