装饰器模式
装饰器模式是一种结构模式,通过装饰器模式可以在不改变原有类结构的情况下向一个新对象添加新功能,是现有类的包装。
图解
角色
- 抽象组件:定义组件的抽象方法
- 具体组件:实现组件的抽象方法
- 抽象装饰器:实现抽象组件接口,聚合具体组件
- 具体装饰器:定义装饰方法,重写抽象组件的抽象方法,并在方法内调用具体组件的方法实现和装饰方法
代码示例
抽象组件:
public interface Shape {void paint();
}
具体组件:
public class Rotundity implements Shape {@Overridepublic void paint() {System.out.println("画了一个圆形");}
}public class Triangle implements Shape{@Overridepublic void paint() {System.out.println("画了一个三角形");}
}
抽象装饰器
public abstract class ShapeDecorator implements Shape{protected Shape shape;public ShapeDecorator(Shape shape) {this.shape = shape;}
}
具体装饰器
/** 颜色装饰*/
public class ColorDecorator extends ShapeDecorator{public ColorDecorator(Shape shape) {super(shape);}@Overridepublic void paint() {shape.paint();filling();}private void filling(){System.out.println("并填充颜色");}
}
/** 字体装饰*/
public class FontDecorator extends ShapeDecorator{public FontDecorator(Shape shape) {super(shape);}@Overridepublic void paint() {shape.paint();changePaint();}public void changePaint(){System.out.println("并加粗了字体");}
}
使用
public class Test {public static void main(String[] args) {Shape triangle = new Triangle();Shape rotundity = new Rotundity();Shape triangleColorDecorator = new ColorDecorator(triangle);Shape rotundityColorDecorator = new ColorDecorator(rotundity);System.out.println("画一个三角形,并填充颜色:");triangleColorDecorator.paint();System.out.println("画一个圆形,并填充颜色,在加粗字体:");FontDecorator fontDecorator = new FontDecorator(rotundityColorDecorator);fontDecorator.paint();}
}
画一个三角形,并填充颜色:
画了一个三角形
并填充颜色
画一个圆形,并填充颜色,在加粗字体:
画了一个圆形
并填充颜色
并加粗了字体