//测试类 public class DecoratorPatternDemo { public static void main(String[] args) { //创建一个圆形对象 Shape circle = new Circle(); //创建一个矩形对象 Shape rectangle = new Rectangle(); //创建一个红色装饰器对象,包装圆形对象 Shape redCircle = new RedShapeDecorator(circle); //创建一个绿色装饰器对象,包装矩形对象 Shape greenRectangle = new GreenShapeDecorator(rectangle);
//调用各个对象的方法,展示不同的效果 System.out.println("Normal circle:"); circle.draw(); System.out.println("Normal rectangle:"); rectangle.draw(); System.out.println("Red circle:"); redCircle.draw(); System.out.println("Green rectangle:"); greenRectangle.draw(); } } ```输出结果如下:``` Normal circle: Drawing a circle Normal rectangle: Drawing a rectangle Red circle: Drawing a circle Setting red border Green rectangle: Drawing a rectangle Setting green border
Spring 代码示例
要想再 Spring 项目中应用装饰器模式,只需对以上代码进行简单改造即可,
给具体组件类 Circle、Rectangle 添加 @Component 注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@Component public class Rectangle implements Shape { @Override public void draw() { System.out.println("Drawing a rectangle"); } }
@Component public class Rectangle implements Shape { @Override public void draw() { System.out.println("Drawing a rectangle"); } }
@Test public void test() { System.out.println("Red circle:"); redCircle.draw(); System.out.println("Green rectangle:"); greenRectangle.draw(); } } ```输出结果如下:``` Red circle: Drawing a circle Setting red border Green rectangle: Drawing a rectangle Setting green border