设计模式之装饰器模式
1 装饰器模式
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构,它是作为现有类的一个包装。
2 类图实现
这里最关键的是我们装饰器类(抽象类)既实现了原始功能接口(Shape接口)又和原始接口是关联关系(Shape接口作为这个抽象装饰类的成员变量)
3 代码实现
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
//Shape redCircle = new RedShapeDecorator(new Circle());
//Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
redCircle.draw();
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
}
4 运行结果
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
5 优点
1)继承的缺点:如果我们用继承的方式增加新功能,继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀
2)装饰器的有点:装饰类和被装饰类可以独立发展,不相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能
部分参考:https://www.runoob.com/design-pattern/decorator-pattern.html
作者:chen.yu
深信服三年半工作经验,目前就职游戏厂商,希望能和大家交流和学习,
微信公众号:编程入门到秃头 或扫描下面二维码
零基础入门进阶人工智能(链接)