针对问题:在两个集合中的对象期望做到任意组合,而这样的组合的可能性是太多了,在实现起来无疑会导致类爆炸。所以必须有一种方法在运行时动态的创建出我期望的类型,有这样的一种解决方案可以做到:让两个集合的对象(装饰者、被装饰者)实现同一接口,也就是说让装饰者、被装饰者属于同一类型,并且在装饰者中组合这一接口,这样装饰者就可以组合(装饰)任意的被装饰者,更重要的是装饰完成之后的类型又可以作为被装饰者来被装饰,然后就可以一直这样循环装饰下去,用这样类似递归的形式就可以在运行时动态的组合出任意我想要的类型了。
装饰者模式结构图:
装饰者模式实现代码:
/**
* 装饰、被装饰的抽象
* @author bruce
*
*/
public abstract class Component {
public void operation(){};
}
/**
* 装饰者抽象(区分主体)
* @author bruce
*
*/
public abstract class Decorator extends Component{
}
/**
* 主体(被装饰)
* @author bruce
*
*/
public class ConcreteComponent extends Component{
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("主体");
}
}
/**
* 装饰者A
* @author bruce
*
*/
public class ConcreteDecoratorA extends Decorator{
/**
* 组合接口
*/
private Component component;
public ConcreteDecoratorA(Component component){
this.component=component;
}
@Override
public void operation() {
System.out.println("为主体装饰A功能");
component.operation();
}
}
/**
* 装饰者B
* @author bruce
*
*/
public class ConcreteDecoratorB extends Decorator{
/**
* 组合接口
*/
private Component component;
public ConcreteDecoratorB(Component component){
this.component=component;
}
@Override
public void operation() {
System.out.println("为主体装饰B功能");
component.operation();
}
}
/**
* 测试
* @author bruce
*
*/
public class Client {
public static void main(String[] args) {
Component component=new ConcreteComponent();//创建主体
Component decoratorA=new ConcreteDecoratorA(component);//创建装饰者A,并装饰主体
System.out.println("----------");
decoratorA.operation();
Component decoratorB=new ConcreteDecoratorB(component);//创建装饰者B,并装饰主体
System.out.println("----------");
decoratorB.operation();
decoratorB=new ConcreteDecoratorB(decoratorA);//创建装饰者B,并装饰decoratorA
System.out.println("----------");
decoratorB.operation();
/**
* output:
* ----------
为主体装饰A功能
主体
----------
为主体装饰B功能
主体
----------
为主体装饰B功能
为主体装饰A功能
主体
*/
}
}