Skip to content

Instantly share code, notes, and snippets.

@bz0
Created July 30, 2018 00:22
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 bz0/f65ff1d22afe1999485b9400733d5f03 to your computer and use it in GitHub Desktop.
Save bz0/f65ff1d22afe1999485b9400733d5f03 to your computer and use it in GitHub Desktop.
GoF Decoratorパターン
<?php
interface Text{
public function getText();
public function setText($str);
}
class PlainText implements Text{
private $textString = null;
public function getText(){
return $this->textString;
}
public function setText($str){
$this->textString = $str;
}
}
//基盤クラス:Textインスタンスのgetter,setterのみ
abstract class TextDecorator implements Text{
private $text;
public function __construct(Text $target){
$this->text = $target;
}
//TextインスタンスのtextStringプロパティから文字列を取得
public function getText(){
return $this->text->getText();
}
//TextインスタンスのtextStringプロパティに文字列をセット
public function setText($str){
$this->text->setText($str);
}
}
//大文字に変換
class UpperCaseText extends TextDecorator{
public function __construct(Text $target){
parent::__construct($target);
}
public function getText(){
$str = parent::getText();
$str = strtoupper($str);
return $str;
}
}
//全角に変換
class DoubleByteText extends TextDecorator{
public function __construct(Text $target){
parent::__construct($target);
}
public function getText(){
$str = parent::getText();
$str = mb_convert_kana($str, "RANSKV");
return $str;
}
}
$string = "abcあいDEFKA";
$text = new PlainText();
$text->setText($string);
//大文字に変換
$UpperCase = new UpperCaseText($text);
echo "UpperCase:" . $UpperCase->getText();
echo "\n";
//かなに変換
$DoubleByte = new DoubleByteText($text);
echo "DoubleByte:" . $DoubleByte->getText();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment