在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

详解java装饰模式(Decorator Pattern)

2016-7-29 15:37| 发布者: zhangjf| 查看: 659| 评论: 0

摘要: 一、装饰器模式(Decorator Pattern) 允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。 这种模式创建了一个装饰类,用来包装原有的类,并 ...

一、装饰器模式(Decorator Pattern)

允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

我们通过下面的实例来演示装饰器模式的使用。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。

二、实现
我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。然后我们创建一个实现了 Shape 接口的抽象装饰类ShapeDecorator,并把 Shape 对象作为它的实例变量。

RedShapeDecorator 是实现了ShapeDecorator 的实体类。

DecoratorPatternDemo,我们的演示类使用 RedShapeDecorator 来装饰 Shape 对象。

步骤 1
创建一个接口。

Shape.java

  1. public interface Shape {
  2. void draw();
  3. }
复制代码

步骤 2
创建实现接口的实体类。

Rectangle.java

  1. public class Rectangle implements Shape {
  2. @Override
  3. public void draw() {
  4. System.out.println("Shape: Rectangle");
  5. }
  6. }
复制代码

Circle.java

  1. public class Circle implements Shape {
  2. @Override
  3. public void draw() {
  4. System.out.println("Shape: Circle");
  5. }
  6. }
复制代码

步骤 3
创建实现了 Shape 接口的抽象装饰类。

ShapeDecorator.java

  1. public abstract class ShapeDecorator implements Shape {
  2. protected Shape decoratedShape;
  3. public ShapeDecorator(Shape decoratedShape){
  4. this.decoratedShape = decoratedShape;
  5. }
  6. public void draw(){
  7. decoratedShape.draw();
  8. }
  9. }
复制代码

步骤 4
创建扩展自 ShapeDecorator 类的实体装饰类。

RedShapeDecorator.java

  1. public class RedShapeDecorator extends ShapeDecorator {
  2. public RedShapeDecorator(Shape decoratedShape) {
  3. super(decoratedShape);
  4. }
  5. @Override
  6. public void draw() {
  7. decoratedShape.draw();
  8. setRedBorder(decoratedShape);
  9. }
  10. private void setRedBorder(Shape decoratedShape){
  11. System.out.println("Border Color: Red");
  12. }
  13. }
复制代码

步骤 5
使用 RedShapeDecorator 来装饰 Shape 对象。

DecoratorPatternDemo.java

  1. public class DecoratorPatternDemo {
  2. public static void main(String[] args) {
  3. Shape circle = new Circle();
  4. Shape redCircle = new RedShapeDecorator(new Circle());
  5. Shape redRectangle = new RedShapeDecorator(new Rectangle());
  6. System.out.println("Circle with normal border");
  7. circle.draw();
  8. System.out.println("nCircle of red border");
  9. redCircle.draw();
  10. System.out.println("nRectangle of red border");
  11. redRectangle.draw();
  12. }
  13. }
复制代码

步骤 6
验证输出。

  1. Circle with normal border
  2. Shape: Circle
  3. Circle of red border
  4. Shape: Circle
  5. Border Color: Red
  6. Rectangle of red border
  7. Shape: Rectangle
  8. Border Color: Red
复制代码

希望本文所述对大家学习java程序设计有所帮助。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 09:16

Copyright 2015-2025 djqfx

返回顶部