設計モードphp例:デザイナモードデザイナモード
2048 ワード
クラスを拡張するには、一般的に継承または組合せの形式を使用します.継承方式で拡張すると,ベースクラスのサブクラスの増加,およびサブクラスのサブクラスの出現に伴い,コードの無制限膨張が出現し,システムの複雑さが増大する.装飾者モードを使用すると、継承と参照が可能になり、クラスのいくつかの機能を動的に拡張し、継承数を減らすことができます.
装飾紙UMLクラス図:
phpコードインスタンス(php設計モードから)
装飾紙UMLクラス図:
phpコードインスタンス(php設計モードから)
/**
*
*/
/**
*
*/
interface Component {
/**
*
*/
public function operation();
}
/**
*
*/
abstract class Decorator implements Component{
protected $_component;
public function __construct(Component $component) {
$this->_component = $component;
}
public function operation() {
$this->_component->operation();
}
}
/**
* A
*/
class ConcreteDecoratorA extends Decorator {
public function __construct(Component $component) {
parent::__construct($component);
}
public function operation() {
parent::operation(); //
$this->addedOperationA(); //
}
/**
* A,
*/
public function addedOperationA() {
echo 'Add Operation A
';
}
}
/**
* B
*/
class ConcreteDecoratorB extends Decorator {
public function __construct(Component $component) {
parent::__construct($component);
}
public function operation() {
parent::operation();
$this->addedOperationB();
}
/**
* B,
*/
public function addedOperationB() {
echo 'Add Operation B
';
}
}
/**
*
*/
class ConcreteComponent implements Component{
public function operation() {
echo 'Concrete Component operation
';
}
}
/**
*
*/
class Client {
/**
* Main program.
*/
public static function main() {
$component = new ConcreteComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($decoratorA);
$decoratorA->operation();
$decoratorB->operation();
}
}
Client::main();