Decorator Pattern dimaksudkan untuk mengubah atau menambah perilaku/fungsionalitas sebuah object/instance dari sebuah class tanpa mengubah perilaku object-object dari class yang sama.
Berikut ini adalah contoh penerapan decorator pattern dengan menggunakan bahasa pemprograman PHP
class ParentClass {
public function __construct(){
// your code
}
public function functionNumberOne(){
// your code
}
}
class DecoratorClass extends ParentClass {
private $decorated;
public function __construct(ParentClass $objectToGetDecorated){
parent::construct();
$this->decorated = $objectToGetDecorated;
// your code
}
public function functionNumberOne(){
// if you want to call the original method then call it :)
$this->decorated->functionNumberOne();
// your code
}
public function newAddedFunction(){
// your code
}
}
$a = new ParentClass;
$b = new ParentClass;
$bDecorated = new DecoratorClass($b);
Perbedaan dengan inheritance/ pewarisan:
- Pewarisan mengubah class
- Decorator mengubah object/instance
Daftar Pustaka
Kontributor Wikipedia. 2013. Decorator pattern. (Online) Wikipedia, The Free Encyclopedia. http://en.wikipedia.org/w/index.php?title=Decorator_pattern&oldid=586454896 . diakses 21 Desember 2013 00:06
Komentar
Posting Komentar