装饰模式
动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的取代方案
代码
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();
}
}
測试类:
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
*/
}
}