设计模式(Java随笔)—装饰模式

装饰模式(Decorator Pattern):为已有功能动态地添加更多功能的一种方式
Attach additional responsiblities to an object dynamically keeping the same interface. Decorator provide a flexible alternative to subclassing for extending functionality.

动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰模式的四个角色:

抽象构件(Component)角色:规范需要装饰的对象(原始对象)
具体构件(Concrete Component)角色:实现抽象构件接口,定义一个需要装饰的原始类
抽象装饰(Decorator)角色:定义一个与抽象构件接口一致的接口,并拥有一个构件对象的实例
具体装饰(Concrete Decorator)角色:实现抽象装饰接口,负责对构建对象进行装饰
装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象。

装饰模式把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效的把类的核心职责与装饰功能区分开,而且可以去除相关类中重复的装饰逻辑。

基本代码实现:

public class DecoratorModel {
/**
* 装饰模式
*/
public static void main(String[] args) {
//1、创建具体构建对象
ConcreteComponent component=new ConcreteComponent();
//2、用装饰A对对象进行包装
ConcreteDecoratorA decoratorA=new ConcreteDecoratorA(component);
//3、在装饰A的基础上用装饰B对对象进行包装
ConcreteDecoratorB decoratorB=new ConcreteDecoratorB(decoratorA);
//4、开始装饰
decoratorB.operation(www.dfgjpt.com/);
}
}

//抽象构建角色
interface Component{
public void operation();
}

//具体构建角色
class ConcreteComponent implements Component{
@Override
public void operation() {
//初始业务代码
System.out.println("具体角色的初始构建");
}
}


//抽象装饰角色
abstract class Decorator implements Component{
private Component component=null;
public Decorator(www.leyou2.net Component component){
this.component=component;
}
public void operation(www.thd540.com){
this.component.operation(www.zhongdayule.cn);
}
}

//具体装饰角色A
class ConcreteDecoratorA extends Decorator{
public ConcreteDecoratorA(Component component) {
super(component);
}
//定义新增的操作
private void addOper(){
System.out.println("具体角色的A装饰");
}
//重写operation方法
public void operation(){
super.operation();//先对对象进行初始化构建
this.addOper();
}
}

//具体装饰角色B
class ConcreteDecoratorB extends Decorator{
public ConcreteDecoratorB(Component component) {
super(component);
}
//定义新增的操作
private void addOper(){
System.out.println("具体角色的B装饰");
}
//重写operation方法
public void operation(){
super.operation();//先对对象进行初始化构建
this.addOper();
}
}
运行结果:

具体角色的初始构建
具体角色的A装饰
具体角色的B装饰
在Java.io包中,很多类的设计,都用到了装饰器模式(如Reader相当于抽象的被装饰者,FileReader相当于具体的被装饰者,BufferedReader相当于装饰)。

猜你喜欢

转载自www.cnblogs.com/qwangxiao/p/9777520.html
今日推荐