09@设计模式—(07)装饰模式
来源:互联网 发布:手机写码软件 编辑:程序博客网 时间:2024/05/29 17:14
装饰模式(Decorator Pattern)在不修改原有对象内部数据结构的情况下往里面添加新的功能。它是结构型模式中的一种,实际上就是用已经存在的类来创建一个包装类。
这种设计模式创建一个装饰类,这个装饰类将包装原有的类,并为它提供附加的功能,同时原有类的方法的签名不变(就是方法名和方法参数都不变,同时返回数据类型也不变)。
具体实现
我们将创建一个Shape接口,然后创建一些实现类来实现这个Shape接口。接着我们创建一个抽象(abstract)类ShapeDecorator去实现Shape接口。同时抽象类中有一个类型为Shape的属性,这个属性作为这个接口的具体实现。新建RedShapeDecorator作为ShapeDecorator的子类。最后创建DecoratorPatternDemo类,我们将在这个类中使用RedShapeDecorator来装饰类型对象。
第一步:创建一个Shape接口
Shape.java
package com.pattern.decorator;public interface Shape { void draw();}
第二步:创建实现类(Rectangle和Circle)实现Shape接口
Rectangle.java
package com.pattern.decorator;public class Rectangle implements Shape{ @Override public void draw() { System.out.println("Shape: Rectangle"); }}
Circle.java
package com.pattern.decorator;public class Circle implements Shape{ public void draw() { System.out.println("Shape: Circle"); }}
第三步:创建抽象的装饰类实现Shape接口
ShapeDecorator.java
package com.pattern.decorator;public abstract class ShapeDecorator implements Shape{ protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } public void draw() { this.decoratedShape.draw(); }}
第四步:创建实现类(RedShapeDecorator)继承ShapeDecorator类
RedShapeDecorator.java
package com.pattern.decorator;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"); }}
第五步:使用RedShapeDecorator来装饰Shape objects
DecoratorPatternDemo.java
package com.pattern.decorator;public class DecoratorPatternDemo { public static void main(String args[]){ Shape circle =new Circle(); System.out.println("Circle with normal border"); circle.draw(); Shape redCircle =new RedShapeDecorator(new Circle()); System.out.println("\nCircle of red border"); redCircle.draw(); Shape rectangle = new Rectangle(); System.out.println("\nRectangle with normal border"); rectangle.draw(); Shape redRectangle =new RedShapeDecorator(new Rectangle()); System.out.println("\nRectangle of red border"); redRectangle.draw(); }}
第六步:验证输出
Circle with normal borderShape: CircleCircle of red borderShape: CircleBorder Color: RedRectangle with normal borderShape: RectangleRectangle of red borderShape: RectangleBorder Color: Red
0 0
- 09@设计模式—(07)装饰模式
- 设计模式—装饰模式(三)
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式(一)——装饰设计模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 设计模式(装饰设计模式)
- 设计模式(装饰设计模式)
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- [JavaWeb]jsp图片ajax异步上传,利用ajaxfileupload
- linux c 定时器
- project 修改实际完成时间 计划完成时间自动也修改了 解决办法
- 在线学习算法FTRL-Proximal原理
- 20160423 PL/SQL Developer连接本地Oracle 11g 64位数据库
- 09@设计模式—(07)装饰模式
- ACM2-1001
- NHibernate重要概念的解释和说明
- PHP基础常见问题
- 单链表的逆转
- 小型网站到大型网站-Mysql优化
- 如何学好PHP
- Bsoj 1322 【练习试题】第K小数
- 课程练习二-1006-Line belt