装饰器模式 -- 设计模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。
思考: 装饰器和原型实现了同一个接口, 然后装饰器包装了原型
package day0319.DecoratorPattern; public class Demo{ public static void main(String[] args){ Circle circle = new Circle(); new RedShapeDecorator(circle).draw(); System.out.println("with out Decorator"); new Circle().draw(); } } interface Shape { void draw(); } abstract class ShapeDecorator implements Shape { Shape shape; public ShapeDecorator(Shape shape){ this.shape = shape; } public abstract void draw(); } class RedShapeDecorator extends ShapeDecorator{ public RedShapeDecorator(Shape shape){ super(shape); } @Override public void draw(){ System.out.println("我先是拿起了一支红色的彩色铅笔"); System.out.println("然后我把画纸铺平"); System.out.println("我小心的将身子趴在桌子上"); super.shape.draw(); System.out.println("最后我小心的把我的作品卷了起来, 放好"); } } /************************** 构造两个shape的实现类 *************************/ class Circle implements Shape { @Override public void draw(){ System.out.println("画了一个圆"); } } class Rectangle implements Shape { @Override public void draw(){ System.out.println("画了一个四边形"); } }