该设计模式创建一个装饰者类包装最初的类,并在保持类签名完整的情况下提供增加的功能。
interface Shape {正方形
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("正方形");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("圆形");
}
}
class Decorator implements Shape {
private Shape shape;
public Decorator(Shape shape) {
this.shape = shape;
}
@Override
public void draw() {
System.out.println("装饰前-----");
shape.draw();
System.out.println("装饰后-----");
}
}
public class Client {
public static void main(String<> args) {
Rectangle rectangle = new Rectangle();
rectangle.draw();
Shape shape = new Decorator(rectangle);
shape.draw();
}
}
装饰前-----
正方形
装饰后-----
创建具体
比如给其加上边框
class RedShapeDecorator extends Decorator {
public RedShapeDecorator(Shape shape) {
super(shape);
}
@Override
public void draw() {
System.out.println("装饰前-----");
shape.draw();
setRedBorder(shape);
System.out.println("装饰后-----");
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("装饰红色边框");
}
}
public class Client {
public static void main(String<> args) {
Rectangle rectangle = new Rectangle();
rectangle.draw();
Shape shape = new Decorator(rectangle);
shape.draw();
RedShapeDecorator redShapeDecorator = new RedShapeDecorator(rectangle);
redShapeDecorator.draw();
}
}
装饰器模式的应用场景:
Decorator模式提供了更加灵活的向对象添加职责的方式,可以使用添加和分离的方法,用装饰在运行时刻增加和删除职责(继承不能做到这一点,继承的功能是静态的,不能动态增删,因此比静态继承更灵活)。