设计模式之装饰器模式
【摘要】 1 装饰器模式
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构,它是作为现有类的一个包装。
2 类图实现
这里最关键的是我们装饰器类(抽象类)既实现了原始功能接口(Shape接口)又和原始接口是关联关系(Shape接口作为这个抽象装饰类的成员变量)
 ...
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
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/103286559
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)