動態的將責任附加到對象上。若要擴展功能,裝飾者提供了比繼承更有彈性的取代方案java
代碼markdown
package gx.component;
/** * 組件:裝飾類和被裝飾類 都要繼承:爲了類型保持一致 * @author always * */
public abstract class Component {
public abstract void description();
public abstract int cost();
}
package gx.component.impl;
import gx.component.Component;
/** * 裝飾類的抽象類 * @author always * */
public abstract class Decorator extends Component{
protected Component component;
}
package gx.component.impl;
import gx.component.Component;
/** * * 被包裝的類 * @author always * */
public class Phone extends Component{
public void description() {
System.out.println("裸機");
}
public int cost() {
return 1900;
}
}
package gx.decorator.impl;
import gx.component.Component;
import gx.component.impl.Decorator;
/** * * 裝飾1:給手機買個殼 * @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("帶了手機殼");
}
public int cost() {
return 50+this.component.cost();
}
}
package gx.decorator.impl;
import gx.component.Component;
import gx.component.impl.Decorator;
/** * * 裝飾2:給手機貼個膜 * @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("貼了膜");
}
public int cost() {
return 20+this.component.cost();
}
}
測試類:this
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("價錢:" + component.cost());
/* * 結果: * 裸機 * 帶了手機殼 * 貼了膜 * 價錢:1970 */
}
}