Decoration mode: The decoration mode dynamically extends the functions of an object without changing the original class file and using inheritance. It creates a packaging object, that is, decoration, to package a real object. The decoration mode is a structural mode. Main roles: (1) the abstract Component role: provides an abstract interface for standard preparation.
Decoration mode: The decoration mode dynamically extends the functions of an object without changing the original class file and using inheritance. It creates a packaging object, that is, decoration, to package a real object. Decoration mode is a structural mode. Main roles: (1) Abstract Component role: provides an abstract interface for standard preparation.
Decoration mode: The decoration mode dynamically extends the functions of an object without changing the original class file and using inheritance. It creates a packaging object, that is, decoration, to package a real object.
The decoration mode is a structural mode.
Main roles:
(1) Abstract Component (Component) Role: provides an abstract interface to standardize the objects to be prepared to receive additional responsibilities.
(2) Concrete Component role: defines a class that will receive additional responsibilities.
(3) Decorator: holds an instance of a Component object and implements an interface consistent with the abstract Component Interface.
(4) The Concrete Decorator role is responsible for adding additional responsibilities to the component object.
The uml class diagram is as follows:
The following is an example of php implementation:
Name. ''; echo $ this-> price. 'meta' ;}} // generate an object. $ Coffee = new coffee (); // $ coffee-> showprice (); // I have generated an object above, it is already running online // but I want to dynamically add features to the coffee object without changing the original class and inheritance relationships. What should I do? // Decoration mode // class decretor extends drink {public $ drink; public function _ construct (drink $ drink) {// wrap the object $ this-> drink = $ drink;} public function showprice () {// implement the original functions of the object, $ this-> drink-> showprice (); $ this-> add (); // new function} public function add () {}}// the specific decoration role class suger extends decretor {public $ price = 1.5; public $ name = 'sugar '; public function add () {echo $ this-> name. ''. $ this-> price; echo 'Total '. ($ this-> drink-> price + $ This-> price). 'meta'; }}$ suger = new suger ($ coffee); $ suger-> showprice ();?>