//(1)创建一个接口 package com.cst.ch10; /** * 创建一个接口 Shape,它描述了一个形状 */ public interface Shape { void draw(); }
//(2) 创建一个实体类 Rectangle,它实现了 Shape 接口表示一个矩形
/** * 创建一个实体类 Rectangle,它实现了 Shape 接口表示一个矩形 */ public class Rectangle implements Shape { @Override public void draw() { System.out.println("Shape: Rectangle"); } }
//(3) 创建一个抽象类 ShapeDecorator,它实现了 Shape 接口并包含一个 Shape 引用
public abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } @Override public void draw() { decoratedShape.draw(); } }
//(4) 创建实体类 RedShapeDecorator,它扩展了 ShapeDecorator 类并添加了一些颜色样式
package com.cst.ch10.impl; import com.cst.ch10.Shape; /** * 创建实体类 RedShapeDecorator,它扩展了 ShapeDecorator 类并添加了一些颜色样式 */ public class RedShapeDecorator extends ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { decoratedShape.draw(); setRedBorder(); } private void setRedBorder() { System.out.println("Border Color: Red"); } }
// (5) 创建客户端
package com.cst.ch10.impl; import com.cst.ch10.Shape; public class Client { public static void main(String[] args) { Shape rectangle = new Rectangle(); Shape redRectangle = new RedShapeDecorator(new Rectangle()); System.out.println("Rectangle with normal border"); rectangle.draw(); System.out.println("\nRectangle of red border"); redRectangle.draw(); } }