文章目录
介绍
描述
装饰器模式设计模式属于结构型模式,是允许向一个现有的对象添加新的功能,进行多次包装,同时又不改变其结构。
特点
优点:装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
实现原理
通常为了扩展一个类的功能经常使用继承方式实现,随着功能的增多,就会导致子类太多,为了在不增加许多子类的情况下扩展类,将拓展功能设置为新的类通过继承/实现 + 组合原本类的方式实现拓展。
适用
-
扩展一个类的功能。
-
动态增加功能,动态撤销。
装饰者模式
实现
第一步:创建抽象类Shape,做为被装饰对象,Circle、Rectangle为子类。
public abstract class Shape {
private String type;
private String des;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public abstract String now();
}
// 子类
public class Circle extends Shape{
public Circle() {
setType("圆形");
setDes("初始化圆形 ");
}
@Override
public String now() {
return super.getDes();
}
}
// 子类
public class Rectangle extends Shape{
public Rectangle() {
setType("矩形");
setDes("初始化矩形");
}
@Override
public String now() {
return super.getDes();
}
}
第二步:创建装饰者Decorator,继承+组合Shape类,Border、Color做为继承子类对原对象进行拓展。
// 创建装饰类 继承+ 组合
public class Decorator extends Shape{
private Shape shape;
public Decorator(Shape shape) {
this.shape = shape;
}
@Override
public String now() {
// 重写 返回 原对象 + 当前描述
return shape.getDes()+ " && " + super.getDes();
}
@Override
public String getDes() {
// 重写 des
return shape.getDes() + " && " + super.getDes();
}
}
// 装饰子类
public class Border extends Decorator{
public Border(Shape shape) {
super(shape);
setDes("添加 2cm 边框");
}
}
// 装饰子类
public class Color extends Decorator{
public Color(Shape shape) {
super(shape);
setDes(" 染绿色");
}
}
第三步:测试。
public class Test {
public static void main(String[] args) {
Shape shape = new Circle(); // 创建被装饰对象
System.out.println(shape.now()); // 输出现在样式
shape = new Border(shape); // 进行 边框装饰
System.out.println(shape.now()); // 输出现在样式
shape = new Color(shape); // 再次进行 颜色装饰
System.out.println(shape.now()); // 输出现在样式
// 初始化圆形
// 初始化圆形 && 添加 2cm 边框
// 初始化圆形 && 添加 2cm 边框 && 染绿色
}
}