设计模式学习笔记——装饰器模式
来源:互联网 发布:mac安装exe软件 编辑:程序博客网 时间:2024/05/01 02:43
设计模式学习笔记——装饰器模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
1.实例
把一个形状装饰上不同的颜色,同时又不改变形状类。
//创建形状接口interface Shape{ void show();}//形状实体类class Rectangle implements Shape{ @Override public void show(){ System.out.println("Shape:Rectangle"); }}class Circle implements Shape{ @Override public void show(){ System.out.println("Shape:Circle"); }}//装饰抽象类abstract class ColorDecorator implements Shape{ protected Shape sp; ColorDecorator(Shape sp){ this.sp=sp; } public void show(){ sp.show(); }}//装饰类class RedColorDecorator extends ColorDecorator{ RedColorDecorator(Shape sp){ super(sp); } @Override public void show(){ sp.show(); System.out.println("Color:Red"); }}class Solution{ public static void main(String []args){ Circle circle = new Circle(); RedColorDecorator redCircle=new RedColorDecorator(new Circle()); RedColorDecorator redRectangle=new RedColorDecorator(new Rectangle()); circle.show(); redCircle.show(); redRectangle.show(); }}
2.总结
- 通常在不想增加太多子类的时候使用装饰器模式扩展类,即替代继承的功能。
- 装饰类和被装饰类可以独立发展,不会相互耦合。
- 但多层装饰比较复杂。
阅读全文
0 0
- 设计模式学习笔记——装饰器模式
- 设计模式学习笔记--装饰器模式
- 设计模式学习笔记——装饰模式
- 设计模式学习笔记——装饰模式
- 设计模式学习笔记——装饰模式
- 设计模式学习笔记——Decorator装饰模式
- 设计模式学习笔记——装饰(Decorator)模式
- 设计模式学习笔记——装饰模式
- 学习笔记——JAVA设计模式<9>装饰模式
- 三、装饰模式——设计模式学习笔记
- 设计模式学习笔记(六)—Decorator装饰模式
- 设计模式笔记——装饰模式
- 《设计模式》学习笔记--装饰器Decorator
- 学习设计模式(5)——装饰器模式
- 设计模式学习笔记-装饰模式
- 设计模式学习笔记--装饰(Decorator)模式
- 设计模式--装饰模式学习笔记
- 设计模式学习笔记--装饰模式
- 文件选择器
- mysql和oracle的区别
- 内部类
- hdu 4496 D-City (并查集)
- kotlin学习的一些学习资源,你需要收藏了
- 设计模式学习笔记——装饰器模式
- 分布式消息队列RocketMQ与Kafka架构上的巨大差异之2 -- CommitLog与ConsumeQueue
- 196. Delete Duplicate Emails
- Y
- sprintf函数用法详解
- [题解]codeforces 438d The Child and Sequence
- Oracle 10g安装教程
- 评教管理系统
- Asp.net创建Datatable并赋值