装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。
装饰模式的结构
具体装饰角色
下面对上面比较官方的说法些通俗的例子。
装饰模式的结构
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。
装饰模式的类图如下:
在装饰模式中的角色有:
● 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
● 具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。
● 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
● 具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。
源代码
抽象构件角色
public interface Component {
public void sampleOperation();
}
具体构件角色
public class ConcreteComponent implements Component {
@Override
public void sampleOperation() {
// 写相关的业务代码
}
}
装饰角色
public class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void sampleOperation() {
// 委派给构件
component.sampleOperation();
}
}
具体装饰角色
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void sampleOperation() {
super.sampleOperation();
// 写相关的业务代码
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void sampleOperation() {
super.sampleOperation();
// 写相关的业务代码
}
}
下面对上面比较官方的说法些通俗的例子。
抽象构件角色:穿衣
具体构件角色:Human
装饰角色:给人穿衣
具体装饰者:穿内衣,穿内裤,穿长裤,穿衬衫,穿外套,穿领带,穿皮鞋,穿高跟鞋
public interface Dress(){
doDress();
}
public human impements Dress{
@override
public void doDress(){
System.out.println("穿衣啦!”);
}
}
public class DressToHuman implement Dress{
Dress dress;
public DressToHuman(Dress dress){
this.dress = dress;
}
@override
public void doDress(){
dress.doDress();
}
}
public class DressShirt extends DressToHuman{
public DressShirt(Dress dress){
super(dress);
}
@override
public void doDress(){
dress.doDress();
System.out.println("穿衬衫");
}
}
当要生成一个穿内裤,衬衫,外套,长裤,皮鞋的人时,我们只需这样生成对象: Dress handsomeMan = new DressLeatherShoes(new DressTrouser(new Dresscoat(new DressShirt(new DressUnderpants(new Human())));
动态给一个对象功能,而不用些各种组合对象对应的类。
再看下JDK中I/O流
其中的filterOutputStream就是对应装饰角色 其各个子类就是具体装饰子类,负责给具体构件角色FileOutputStream,ObjectOutPutStream等添加功能。
装饰者模式很好的体现了多用组合,少用继承
详细解读:http://www.cnblogs.com/shipengzhi/articles/2086419.html