设计模式-装饰者模式

设计模式-装饰者模式

装饰者模式(Decorator)

  • 装饰者模式(Decorator Pattern)也称为包装模式(Wrapper Pattern),以透明动态的方式来动态扩展对象的功能,也是继承关系中一种代替方案
  • 装饰者模式与继承关系的目的都是要扩展对象的功能,但是装饰者模式可以提供比继承更多的灵活性。(减少代码的冗余)
  • 通过不同具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。

mark

  • Component: 抽象组件(可以是抽象类或者接口),被装饰的原始对象
  • ConcreteComponent:具体的实现类,被装饰的具体对象
  • Decorator : 抽象的装饰者,职责就是为了装饰我们的组件对象,内部一定要有一个指向组件的对象引用。
  • ConcreteDecoratorA:装饰者具体实现类,只对抽象装饰者做出具体实现
  • ConcreteDecoratorB:同上

解决的问题

  1. 在某些情况下我们可能会过度的使用继承来扩展对象的功能,由于继承为类型引入了静态的特质,使得这种扩展方式缺乏灵活性,

  2. 并且随着子类的增多(扩展功能的增多) 各种子类的组合(扩展功能)会导致更多子类急剧的膨胀

装饰者模式定义:

  • 动态组合的给一个对象增加一些额外的职责

  • 一般只有装饰者模式的装饰类才会既继承一个类又会组合一个类

举个例子:

  1. 人定义为抽象类,有一个抽象方法eat()
1
2
3
public abstract class Person {
public abstract void eat();
}
  1. 创建一个NormalPerson类继承Person,对eat()方法有了具体实现;
1
2
3
4
5
public class NormalPerson extends Person {
public void eat() {
System.out.println("吃饭");
}
}
  1. 定义一个PersonFood类来表示装饰者的抽象类,保持了一个对Person的引用,可以方便调用具体被装饰的对象方法,这样就可以方便的对其进行扩展功能,并且不改变原类的层次结构。
1
2
3
4
5
6
7
8
9
10
11
12
public class PersonFood extends Person {
private Person person;

public PersonFood(Person person){
this.person = person;
}

@Override
public void eat() {
person.eat();
}
}
  1. 接着就是具体的装饰类了,这两个类没有本质上的区别,都是为了扩展PersonFood类,不修改原有类的方法和结构
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class ExpensiveFood extends PersonFood {
public ExpensiveFood(Person person) {
super(person);
}

@Override
public void eat() {
super.eat();
eatSteak();
drinkRedWine();
}

public void eatSteak(){
System.out.println("吃牛排");
}

public void drinkRedWine(){
System.out.println("喝拉菲");
}

}

public class CheapFood extends PersonFood {
public CheapFood(Person person) {
super(person);
}

@Override
public void eat() {
super.eat();
eatNoodles();
}

public void eatNoodles(){
System.out.println("吃面条");
}
}

Client:测试

1
2
3
4
5
6
7
8
9
10
11
public class Client {
public static void main(String[] args){
Person person = new NormalPerson();

PersonFood cheapFood = new CheapFood(person);
cheapFood.eat();

PersonFood expensiveFood = new ExpensiveFood(person);
expensiveFood.eat();
}
}

总结:

  • 优点
    • 装饰者模式与继承关系的目的都是要扩展对象的功能,但是装饰者模式可以提供比继承更多的灵活性。
    • 通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合

与代理模式的区别:

  • 其实装饰着模式和代理模式很想,但两个目的不尽相同
  • 装饰者模式是以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,目的是为了减少类的冗余
  • 代理模式是提供一个代理对象,并有代理对象来控制原来对象的引用。
  • 总而言之:代理模式是为了对代理对象进行控制,但不做功能的扩展;装饰者模式为本装饰的对象进行功能的扩展。

未使用装饰者模式和使用装饰者模式 类数量变化

  1. 未使用

mark

  1. 使用了装饰者模式

mark

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信