装饰(Decorator)模式

本文详细介绍了装饰模式的概念及其在Java中的应用。装饰模式是一种用于在不改变对象结构的情况下动态地给对象添加新的职责的设计模式。文章通过示例展示了如何通过装饰模式为对象添加额外功能,并解释了装饰模式的主要角色。
装饰(Decorator)模式:也叫包装模式,Adaptor模式也可以叫包装模式,不过有本质的区别,Adaptor模式没有使原有功能增强
Decorator模式使原有功能增强,而且不是通过子类来实现功能增强的。

装饰模式主要特色:

1.用来扩展特定[color=red]对象[/color]的功能,[color=red]不是扩充某个类的功能[/color]。
2.不需要子类,防止由于子类而导致的复杂和混乱
3.对于一个给定的对象,同事可能有不同的装饰对象,客户端可以通过它的需要选择合适的装饰对象

java.io包下类大量使用到装饰模式。

装饰模式主要角色
1.抽象构件角色:给出一个抽象接口,以规范准备接受附加责任的对象
2.具体构件角色:定义一个将要接收附加责任的类
3.装饰角色:[color=red]持有一个构件对象的实例[/color],并定义一个与抽象构件接口一致的接口
4.具体装饰角色:负责给构件对象"贴上"附加的责任



package com.pattern.decorator;
/**
* 抽象构件角色
*/
public interface Component {

public void doSomething();
}



package com.pattern.decorator;
/**
* 具体构件角色
*/
public class ConcreteComponent implements Component {

public void doSomething() {
System.out.println("功能A");
}

}



package com.pattern.decorator;
/**
* 装饰角色
*/
public class Decorator implements Component {
//拥有一个抽象构件对象
private Component component;
public Decorator(Component component){
this.component = component;
}
public void doSomething() {
component.doSomething();
}

}



package com.pattern.decorator;
/**
* 具体装饰角色一
*/
public class ConcreteDecorator1 extends Decorator {

public ConcreteDecorator1(Component component){
super(component);
}

public void doSomething(){
super.doSomething();
this.doAnotherthing();

}
private void doAnotherthing(){
System.out.println("功能B");
}
}



package com.pattern.decorator;
/**
* 具体装饰角色二
*/
public class ConcreteDecorator2 extends Decorator {

public ConcreteDecorator2(Component component){
super(component);
}

public void doSomething(){
super.doSomething();
this.doAnotherthing();

}
private void doAnotherthing(){
System.out.println("功能C");
}
}



package com.pattern.decorator;
/**
* 客户端
*/
public class Client {

public static void main(String[] args){
//扩充了component 对象的功能。
Component component = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
component.doSomething();
}
}



运行结果:
功能A
功能B
功能C
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值