装饰者模式(Decorator Pattern)允许在不改变结构的情况下向已经存在的类添加新的功能。这种类型的设计模式给已存在的类进行包装,属于结构型模型。
该设计模式创建一个装饰者类包装最初的类,并在保持类签名完整的情况下提供增加的功能。
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();
}
}正方形
装饰前-----
正方形
装饰后-----
创建具体具体的装饰对象继承Decorator,起到给shape添加功能。
比如给其加上边框
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模式提供了更加灵活的向对象添加职责的方式,可以使用添加和分离的方法,用装饰在运行时刻增加和删除职责(继承不能做到这一点,继承的功能是静态的,不能动态增删,因此比静态继承更灵活)。