深入设计模式-7.装饰模式
来源:互联网 发布:淘宝发货后退款流程 编辑:程序博客网 时间:2024/06/08 07:37
1.简介
装饰模式:动态地给一个对象添加一些额外的职责。
通过继承方法也可以实现装饰模式所能实现的部分功能,但是和继承相比,装饰模式更加灵活。譬如装饰一个电视墙,我们可以给每一个电视墙的种类都继承添加边框的方法,但是有些种类并不需要添加边框的方法,而且可能其他种类电视墙需要的是其他方法,在java中不支持多继承,这样就造成了不必要的浪费及不可实现性。而我们通过装饰模式可以完美解决这种问题,只有在需要装饰的时候添加边框,而且可以递归循环多次装饰。
装饰模式主要适用于以下情况:
1、在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
2、处理那些可以撤销的职责。
3、当不能采用声称子类的方法进行扩充的时候。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
装饰模式在java.io包中被大量使用。
2.结构
3.示例
public interface IDeciratorPerson(){
public void dress();
}
public class DeciratorPerson implementsIDeciratorPerson(){
public void dress(){
System.out.println("穿风衣! ");
}
}
//装饰1
public classDeciratorPersonOne implementsIDeciratorPerson(){
privateIDeciratorPerson deciratorPerson;
publicDeciratorPersonOne(IDeciratorPerson deciratorPerson){
this.deciratorPerson = deciratorPerson;
}
public void dress(){
System.out.println("穿皮鞋! ");
}
}
//装饰2
public class DeciratorPersonTwo implements IDeciratorPerson(){
private IDeciratorPerson deciratorPerson;
public DeciratorPersonOne(IDeciratorPerson deciratorPerson){
this.deciratorPerson = deciratorPerson;
}
public void dress(){
System.out.println("穿西裤! ");
}
}
//主函数public class Main(){
public static void main(String[] args){
IDeciratorPerson idp = new DeciratorPerson();
IDeciratorPerson dp = new DeciratorPersonTwo(new DeciratorPersonOne(idp)) ;
dp.dress();
}
}
4.优缺点
1.优点:
1.比继承更加灵活。继承机制要求为每个添加的职责创建一个新的子类,这样会产生很多新的类,并且会增加系统的复杂度。
2.避免在层次结构高层的类有太多的特征。装饰模式提供一种“即用即付”的方法添加职责。它并不在一个复杂的可定制的类中支持所有特征你可以定义一个简单的类,并且使用装饰类给它逐渐添加功能。
2.缺点
1.有许多小对象。采用装饰模式会产生很多看上去类似的小对象,对后期的排错造成很大障碍。
- 深入设计模式-7.装饰模式
- 设计模式深入学习---Decorator装饰模式(结构型模式)
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式 装饰模式
- 设计模式----装饰模式
- 设计模式-【装饰模式】
- 设计模式--装饰模式
- 设计模式装饰模式
- 设计模式 - 装饰模式
- 设计模式-----装饰模式.
- 设计模式-----装饰模式.
- [ 设计模式 ] 装饰模式!
- 设计模式:装饰模式
- JavaScript 对this的理解
- 线程句柄作WaitForSingleObject的参数是什么意思?
- OpenGL 矩阵变换(讲的太好了~!)
- HDU2037 活动安排 贪心
- android源码问题解答之一(输入法)
- 深入设计模式-7.装饰模式
- Unity3D项目程序加密1——在Unity3D里使用自己的dll
- MySQL WorkBench中利用外键实现级联删除、更新
- 解决Fragment already active方法
- myEclipse debug
- 节前互联网公司开启“红包大战”模式
- android屏幕长度单位(dp与px)
- 【已解决】奇葩4: iOS定位,iPhone可以很快定位,但是iPad一直定位不了
- CentOS中安装gcc编译器