简述
设计模式中的装饰模式,是在已有的功能状态下,向旧的类添加新的功能时,可以避免修改旧代码的设计模式。
例如:一个人,穿衣服、裤子、鞋子…等功能都属于人的装饰,并且每个人选择的装饰可以有区别,可以独立分开和搭配;另外,在购买新的装饰时(新添加新的功能),只需要继承原有的装饰类并实现对应装饰的功能即可,与之前的其他装饰或人完全解藕。
UML图示
代码示例
装饰相关类
/**
* 装饰器
* @author: Kellan_Song
* @date: 2021-01-15 23:58
**/
public abstract class Decorator {
Decorator d;
protected Person show(Person person) {
if (d != null) {
d.show(person);
}
return person;
}
protected void setDecorator(Decorator d) {
this.d = d;
}
Decorator(Decorator d) {
this.d = d;
}
public Decorator(){
}
}
/**
* 装饰- T-Shirt
* @author: Kellan_Song
* @date: 2021-01-16 00:27
**/
public class Shirt extends Decorator {
public Shirt() {
}
public Shirt(Decorator t) {
super(t);
}
public Person show(Person person) {
if (person.name != null) {
System.out.println(person.name + " 穿T-Shirt");
super.show(person);
}
return person;
}
}
/**
* 装饰-鞋子
* @author: Kellan_Song
* @date: 2021-01-16 00:29
**/
public class Shoes extends Decorator {
...此处省略...
}
/**
* 装饰-裤子
* @author: Kellan_Song
* @date: 2021-01-16 00:29
**/
public class Pants extends Decorator {
...此处省略...
}
被装饰相关
/**
* 人类
* @author: Kellan_Song
* @date: 2021-01-15 23:38
**/
public abstract class Person {
String name;
public Decorator decorator;
public Decorator getDecorator() {
return decorator;
}
public Person setDecorator(Decorator decorator) {
this.decorator = decorator;
return this;
}
public void show() {
if (decorator != null) {
decorator.show(this);
}
}
}
/**
* 男人
* @author: Kellan_Song
* @date: 2021-01-16 00:09
**/
public class Man extends Person {
public Man() {
}
public Man(String name) {
this.name = name;
}
}
示例
public class Main {
public static void main(String[] args) {
Man kellan = new Man("Kellan");
kellan.setDecorator(new Shirt(new Pants(new Shoes())));
kellan.show();
}
}
-- 输出结果
Kellan 穿T-Shirt
Kellan 穿裤子
Kellan 穿鞋子
缺点
每个对应的装饰都需要新建一个类进行独立管理,且类型需要高度一致;若需求改动使其中一个与其他不同,则改动大。