装饰模式
装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。 即通过不同的组合方式,可以组合出各种不同的行为。
装饰模式结构图如下:
装饰模式的基本代码实现:
//Component类
abstract class Component{
//对象操作模板方法
public abstract void Operation();
}
//ConcreteComponent类
class ConcreteComponent extends Component{
@Override
public void Operation(){
print("具体对象操作。。。")
}
}
//Decorator类
abstract class Decorator extends Component{
protected Component component;
//设置 Conponent
public void setComponent(Component component){
this.component = component;
}
//重写Operation(),实际执行的是 Component的 Operation()
@Override
public void Operation(){
if(component != null){
component.Operation();
}
}
}
//ConcreteDecoratorA类
class ConcreteDecoratorA extends Decorator{
//本类独有的功能
private String addState;
// //首先运行原 Component的Operation(),再执行本类功能,相当于对原Component做了装饰
@Override
public void Operation(){
Super.Operation();
addState = "装饰一个字段";
print("具体装饰对象A的功能")
}
}
//ConcreteDecoratorB类
class ConcreteDecoratorB extends Decorator{
//首先运行原 Component的Operation(),再执行本类功能,相当于对原Component做了装饰
@Override
public void Operation(){
Super.Operation();
AddedBehavior();
print("具体装饰对象B的功能")
}
//本类独有的方法,以区别于concreteDecoratorA
private void AddedBehavior(){
}
}
//客户端代码
public static void main(String[] args){
ConcreteComponent cc = new ConcreteComponent();
ConcreteDecoratorA cd1 = new ConcreteDecoratorA();
ConcreteDecoratorB cd1 = new ConcreteDecoratorB();
cd1.setComponent(cc); //在ConcreteDecoratorA 中对 cc修饰
cd2.setComponent(cd1); //在ConcreteDecoratorB 中对 cd1修饰
cd2.Operation();
}
基于对装饰模式的分析可以看出,装饰模式是利用 setComponent()来对对象进行包装的。每个装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关系如何被添加到对象链中。
如果只有一个ConcreteComponent类而没有抽象的Conponent类,那Decorator类可以是ConcreteComponent的子类。同理如果只有一个ConcreteDecorator子类,就没有必要在建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并为一个类。
装饰模式的特点:
装饰对象和真实对象有相同的接口。
装饰对象中包含一个真实对象的引用。
装饰对象可以接收所有客户端的请求,并将这些请求转发给真实对象。并且可以在转发这些请求之前或之后增加一些功能。
通过使用不同的装饰类以及自由的排列组合装饰类,可以制造出很多中不同的行为组合。
再来提一个简单的需求:通过装饰模式实现不同的穿着搭配,只要在客户端通过自由组合具体装饰类即可。
需求分析类图如下:
具体代码就靠自己写啦~~