装饰模式的英文原文是:Attach additional responsibilitities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality. 意思是:动态的给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式有四个角色,分别是:
1、抽象构件角色:这个角色是被装饰角色的规范。
2、具体构件角色:该角色是具体被装饰的角色,实现抽象构件的接口。
3、装饰角色:这个角色有一个具体被装饰构件角色的对象的实例,并且实现了抽象构件的接口。
4、具体装饰角色:该角色具体执行对对象的装饰。
装饰模式类图:
各个类的实现代码:
抽象构件:
package com.zz.decorator;
/**
* 抽象构件
* Copyright 2015年4月20日
* created by txxs
* all right reserved
*/
public interface Component {
public void operation();
}
具体构件:
package com.zz.decorator;
/**
* 具体构建
* Copyright 2015年4月20日
* created by txxs
* all right reserved
*/
public class ConcreteComponent implements Component {
@Override
public void operation() {
//业务代码
}
}装饰角色:
package com.zz.decorator;
/**
* 装饰角色
* Copyright 2015年4月20日
* created by txxs
* all right reserved
*/
public abstract class Decorator implements Component{
private Component component = null;
public Decorator(Component component){
this.component = component;
}
public void operation(){
this.component.operation();
}
}
具体装饰角色:
package com.zz.decorator;
/**
* 具体装饰角色
* Copyright 2015年4月20日
* created by txxs
* all right reserved
*/
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
//定义自己的方法
private void method(){
//业务代码
}
//重写operation方法
public void operation(){
this.method();
super.operation();
}
}
测试类:
package com.zz.decorator;
/**
* 测试类
* Copyright 2015年4月20日
* created by txxs
* all right reserved
*/
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component = new ConcreteDecorator(component);
component.operation();
}
}
装饰模式的优点:
1、装饰模式可以动态的添加一个实现类的功能
2、装饰类和被装饰类可以独立,不会相互耦合。
3、Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
实例:通过设计组装和升级大众CC来说明装饰模式,有一个VolkCC类实现Volk接口,设计一个CCDecorator实现Volk这个接口,在ConcreteCCDecorator这个具体装饰角色中进行功能的增加和重写。源码下载
实现效果:
哈哈,正在学习中……
原文地址:http://blog.csdn.net/maoyeqiu/article/details/45156817