无涯教程-Java 装饰器模式

65 阅读1分钟

装饰器模式就可以将新函数动态地附加于现有对象而不改变现有对象的函数,这种设计模式属于结构模式。

无涯教程通过以下示例演示装饰图案的使用,在该示例中,将使用某种颜色装饰形状而不改变形状类别。

装饰器模式实例

将创建一个 Shape 接口和实现 Shape 接口的具体类。然后将创建一个抽象装饰器类ShapeDecorator,该类实现Shape接口并将Shape对象作为实例变量。

RedShapeDecorator 是实现 ShapeDecorator 的具体类。

DecoratorPatternDemo ,演示类将使用 RedShapeDecorator 装饰 Shape 对象。

Decorator Pattern UML Diagram

第1步  -  创建一个Shape接口。

Shape.java

public interface Shape {
   void draw();
}

第2步  -  创建实现Shape接口的具体类。

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"); } }

第3步  -  创建实现 Shape 接口的抽象装饰器类。

ShapeDecorator.java

public abstract class ShapeDecorator implements Shape {
   protected Shape decoratedShape;

public ShapeDecorator(Shape decoratedShape){ this.decoratedShape = decoratedShape; }

public void draw(){ decoratedShape.draw(); } }

第4步  -  创建扩展 ShapeDecorator类的具体装饰器类。

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"); } }

第5步  -  使用 RedShapeDecorator 装饰Shape对象

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("\nCircle of red border");
  redCircle.draw();

  System.out.println("\nRectangle of red border");
  redRectangle.draw();

} }

第6步  -  验证输出。

Circle with normal border
Shape: Circle

Circle of red border Shape: Circle Border Color: Red

Rectangle of red border Shape: Rectangle Border Color: Red

参考链接

www.learnfk.com/design-patt…