Java Decorator and javadecorator
Decoration Mode
Dynamically attaches the responsibility to the object. If you want to extend the function, the modifier provides a more flexible alternative solution than inheritance.
Code
Package gx. component;/*** Component: the decoration class and the decorated class must be inherited: to maintain the same type * @ author always **/public abstract class component {public abstract void description (); public abstract int cost ();}
Package gx. component. impl; import gx. component. Component;/*** abstract class of the decoration class * @ author always **/public abstract class Decorator extends Component {protected Component ;}
Package gx. component. impl; import gx. component. component;/***** encapsulated class * @ author always **/public class Phone extends Component {public void description () {System. out. println ("bare metal");} public int cost () {return 1900 ;}}
Package gx. decorator. impl; import gx. component. component; import gx. component. impl. decorator;/***** decoration 1: Buy a shell for your mobile phone * @ author always **/public class DaiKe extends Decorator {public DaiKe () {} public DaiKe (Component component) {this. component = component;} public void description () {this. component. description (); System. out. println ("with mobile phone case");} public int cost () {return 50 + this. component. cost ();}}
Package gx. decorator. impl; import gx. component. component; import gx. component. impl. decorator;/***** decoration 2: attach a film to the mobile phone * @ author always **/public class TieMo extends Decorator {public TieMo () {} public TieMo (Component component) {this. component = component;} public void description () {this. component. description (); System. out. println ("film attached");} public int cost () {return 20 + this. component. cost ();}}
Test class:
Package gx; import gx. component. component; import gx. component. impl. phone; import gx. decorator. impl. daiKe; import gx. decorator. impl. tieMo; import junit. framework. testCase; public class TestDecorator extends TestCase {public void testDecorator () {Component component = new TieMo (new DaiKe (new Phone (); component. description (); System. out. println ("Price:" + component. cost ();/** result: * bare metal * with mobile phone case * with film * price: 1970 */}}