-
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。
-
抽象组件:可以是抽象类或接口,是被装饰类的原始对象
-
组件具体实现类:该类是抽象组件的具体实现,也是我们装饰的具体对象。
-
抽象装饰者:为了装饰我们的组件对象,其内部一定要有一个指向组件对象的引用。在大多数情况下,该类为抽象类,需要根据不同的装饰逻辑实现不同的子类。如果装饰逻辑单一,只有一个的情况下我们可以省略该类直接作为具体的装饰者。
-
具体装饰者:对抽象装饰做具体的实现。
(1)装饰设计模式
- 抽象组件类
public interface Person {
String combination();
}
- 具体组件实现类
public class PersonZ implements Person {
@Override
public String combination() {
return "小张";
}
}
public class PersonL implements Person {
@Override
public String combination() {
return "小李";
}
}
public class PersonW implements Person {
@Override
public String combination() {
return "小王";
}
}
- 抽象的装饰者
public abstract class PersonDecorator implements Person {
private Person person;
public PersonDecorator(Person person) {
this.person = person;
}
@Override
public String combination() {
return person.combination();
}
}
具体的装饰者
public class RedPants extends PersonDecorator {
public RedPants(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show(){
return "红色上衣";
}
}
public class WhitePants extends PersonDecorator {
public WhitePants(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show(){
return "白色上衣";
}
}
public class RedJacket extends PersonDecorator {
public RedJacket(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show() {
return "红色裤子";
}
}
public class WhiteJacket extends PersonDecorator {
public WhiteJacket(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show(){
return "白色裤子";
}
}
public class RedShoes extends PersonDecorator {
public RedShoes(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show(){
return "红色鞋子";
}
}
public class WhiteShoes extends PersonDecorator {
public WhiteShoes(Person person) {
super(person);
}
@Override
public String combination() {
return super.combination() + show();
}
private String show() {
return "白色鞋子";
}
}
- 具体调用
Person person = new PersonZ();
PersonDecorator redPants = new RedPants(person);
redPants.combination();
PersonDecorator whiteJacket = new WhiteJacket(person);
whiteJacket.combination();
PersonDecorator whiteShoes = new WhiteShoes(person);
whiteShoes.combination();
优点
- 采用组合的方式,可以动态的扩展功能,同时也可以在运行时选择不同的装饰器,来实现不同的功能。
- 有效避免了使用继承的方式扩展对象功能而带来的灵活性差,子类无限制扩张的问题。
- 被装饰者与装饰者解偶,被装饰者可以不知道装饰者的存在,同时新增功能时原有代码也无需改变,符合开放封闭原则。
缺点
- 装饰层过多的话,维护起来比较困难。
- 如果要修改抽象组件这个基类的话,后面的一些子类可能也需跟着修改,较容易出错。
网友评论