Decoration mode
Dynamically attaches the responsibility to the object. To extend functionality, decorators offer a more resilient alternative than inheritance
Code
package gx.component;/** * 组件:装饰类和被装饰类 都要继承:为了类型保持一致 * @author always * */publicabstractclass Component { publicabstractvoiddescription(); publicabstractintcost();}
package gx.component.impl;< Span class= "Hljs-keyword" >import gx.component.Component; /** * Decorative class abstract class * @author always * */ public abstract class decorator extends Span class= "Hljs-title" >component { protected Component Component;}
package gx.component.impl;< Span class= "Hljs-keyword" >import gx.component.Component; /** * * Wrapped class * @author always * */ public class phone extends component { public void description () {System.out.println (); } public int cost () {return 1900 ; }}
PackageGx.decorator.impl;ImportGx.component.Component;ImportGx.component.impl.Decorator;/** * Decorate 1: Buy a shell for your 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 the phone case."); } Public int Cost() {return -+ This. Component.cost (); }}
PackageGx.decorator.impl;ImportGx.component.Component;ImportGx.component.impl.Decorator;/** * Decorate 2: Put a film on your 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 ("The film was taped."); } Public int Cost() {return -+ This. Component.cost (); }}
Test class:
PackageGxImportGx.component.Component;ImportGx.component.impl.Phone;ImportGx.decorator.impl.DaiKe;ImportGx.decorator.impl.TieMo;ImportJunit.framework.TestCase; Public class testdecorator extends TestCase { Public void Testdecorator() {Component Component =NewTiemo (NewDaike (NewPhone ())); Component.description (); System.out.println ("Price:"+ Component.cost ());/* Results: * Bare metal * with phone case * affixed with film * Price: 1970 * *}}
Java decorating mode (Decorator)