设计模式学习笔记--装饰器模式
来源:互联网 发布:淘宝怎么借贷 编辑:程序博客网 时间:2024/04/30 09:25
十、装饰器模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时不改变其结构。
通过创建一个装饰类,包装原有的类,保持原有类的方法签名不变,提供额外功能。
介绍
动态的给一个对象添加一些额外的新功能,相比生成子类更为灵活。
相比使用继承,装饰模式避免了由继承而引入的静态特征和子类臃肿的现象。
- 优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代方式,可以动态扩展一个现有类的功能。
- 缺点:多层装饰比较复杂。
实现
创建一个Shape
接口和实现该接口的实体类,然后欻功能键一个实现Shape
接口的装饰类ShapeDecorator
并把Shape
对象作为它的实例变量。RedShapeDecorator
实现ShapeDecorator
的实体类,完成功能扩展。
- 创建接口
Shape.java
public interface Shape { void draw();}
- 创建接口实现类
Rectangle.java
public class Rectangle implements Shape { @override public void draw(){ System.out.println("Shape : Rectangle"); }}
Circle.java
public class Circle implements Shape { @override public void draw(){ System.out.println("Shape : Circle"); }}
- 创建抽象的装饰类
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape{ protected Shape decorateShape; public ShapeDecorator(Shape decorateShape){ this.decorateShape = decorateShape; } public void draw(){ decorateShape.draw(); }}
- 创建实体的装饰类
RedShapeDecorator.java
public class RedShapeDecorator extends ShapeDecorator{ public RedShapeDecorator(Shape decoratedShape){ super(decoratedShape); } @override public void draw(){ decoratedShape.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape){ System.out.println("Border Color : Red"); }}
- 演示
DecoratorPatternDemo.java
public class DecoratorPatternDemo { public static void main(String[] args){ Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Circle with normal border"); circle.draw(); System.out.println("\n Circle of red border"); redCircle.draw(); System.out.println("\n Rectangle of red border"); redRectangle.draw(); }}
- 输出
Circle with normal borderShape: CircleCircle of red borderShape: CircleBorder Color: RedRectangle of red borderShape: RectangleBorder Color: Red
0 0
- 设计模式学习笔记--装饰器模式
- 《设计模式》学习笔记--装饰器Decorator
- 设计模式学习笔记-装饰模式
- 设计模式学习笔记--装饰(Decorator)模式
- 设计模式--装饰模式学习笔记
- 设计模式学习笔记--装饰模式
- [设计模式学习笔记]DECORATOR装饰模式
- 设计模式学习笔记-装饰模式
- 设计模式学习笔记之装饰模式
- 设计模式-装饰者模式学习笔记
- Head First 设计模式学习笔记(3)---装饰器模式
- 设计模式学习笔记之装饰器模式
- 研磨设计模式学习笔记之装饰器模式
- 设计模式学习笔记——装饰器模式
- 设计模式笔记十:装饰器模式
- 设计模式学习----装饰器模式
- 设计模式学习之装饰器模式
- 设计模式学习-装饰器模式
- Android播放GIF动画
- 多态(Polymorphism)
- function标签库取长度函数
- 错误:compress png files error
- Spring Cloud构建微服务架构(四)分布式配置中心
- 设计模式学习笔记--装饰器模式
- IT项目管理
- ble蓝牙技术
- fork入门进阶
- Fragment创建
- Google Calendar (Android Studios上可运行)
- 关于JNI的调试小工具设置
- palsquare-各进制回文数<uscao>1.2
- Spring Boot整合MyBatis