《大话设计模式》之装饰模式
来源:互联网 发布:nginx 跳转到指定端口 编辑:程序博客网 时间:2024/05/17 04:40
1.定义
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
2.针对问题
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
装饰模式是为已有功能动态地添加更多功能的一种方式。
何时使用:
1)取代因基本功能的排列组合而产生非常大量的类2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。3)某个对象的职责经常发生变化或者经常需要动态添加职责,避免为了适应这种变化造成的继承拓展方法.
优点:有效地把类中的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑。
3.实现
//相当与Component,定义一个对象接口,可以给这些对象动态地添加职责public interface Operation { public void show();}
//相当于ConcreteComponent,定义一个具体的对象,可以给这个对象添加新的职责public class Person implements Operation{ private String name; public Person(String name) { this.name = name; } @Override public void show() { System.out.println(name+"穿了:"); }}
//相当于Decorator,装饰类public class Finery implements Operation{ private Operation operation; public Finery(Operation operation) { super(); this.operation = operation; } @Override public void show() { if(operation!=null) { operation.show(); } }}
//具体的装饰对象,起到给Componet添加职责的功能public class TShirts extends Finery { public TShirts(Operation operation) { super(operation); } @Override public void show() { super.show(); System.out.print("big TShirts***"); }}public class BigThrouser extends Finery { public BigThrouser(Operation operation) { super(operation); } public void show() { super.show(); System.out.print("BigThrouser***"); }}
//调用public class Maintest { public static void main(String[] args) { Operation person=new Person("ting"); person=new BigThrouser(person); person=new TShirts(person); person.show(); }}
阅读全文
0 0
- 大话设计之装饰模式
- 大话设计模式之装饰设计模式
- 大话设计模式之-----装饰模式
- 大话设计模式之装饰模式
- 大话设计模式之装饰模式
- 大话设计模式之装饰模式
- 大话设计模式之装饰模式
- 大话设计模式之装饰者模式
- 大话设计模式之装饰器模式
- 三、大话设计模式 之 装饰模式
- 大话设计模式之装饰者模式
- 大话设计模式读后感之装饰模式
- 大话设计模式之装饰模式
- 大话设计模式之装饰模式
- 《大话设计模式》之装饰模式
- 大话设计模式-装饰模式
- 大话设计模式-装饰模式
- 大话设计模式-装饰模式
- 有关Oracle最大连接数的问题
- using namespace的使用问题
- java文本的字符串替换
- 织梦顶级栏目点击后显示第一个子栏目的方法
- Cortex-M3 NVIC与中断控制
- 《大话设计模式》之装饰模式
- 苹果证书导出p12文件
- SourceTree 免登录跳过初始设置的方法
- ORB特征提取算法分析与实现,算法分解
- 微信小程序开发
- Linux互斥锁
- 目标检测(一)目标检测评价指标
- 常用热电偶类型介绍
- 竖向ScrollView嵌套横向滑动布局冲突