1. 目的
动态的给对象添加功能,以达到松散耦合的目的。
2. 什么是装饰者
动态的给对象添加功能,并且不影响其对象结构
3. 解决什么问题
1、继承是属于紧密耦合,不便于系统架构扩展
2、解决子类膨胀
4. 如何解决
将具体功能职责划分,同时继承装饰者模式。
5. 好处
不需要修改被装饰类的任何地方,通过装饰类可以动态的添加对象的功能。以达到解耦的目的
6. 坏处
业务逻辑更加的复杂
7. 角色分配
角色 | 作用 |
---|---|
组件接口 | 组件接口是装饰者和被装饰者额超类 |
具体组件 | 具体组件实现了组件接口的核心方法,完成某一个具体的业务逻辑 |
装饰者 | 实现组件接口,并持有一个具体的被装饰者对象 |
具体装饰者 | 具体的装饰者业务逻辑,即实现了被分离的各个增强的功能点。 |
8. 业务场景
/**
* 业务场景:基类动物(animal),具有吃的功能(eat方法),子类有猫(cat)、狗(dog)。都是实现了吃的功能。
* 现在需要增加动物跑的功能(run)功能。按照继承的原则,需要在基类动物(animal)增加跑的功能(run方法)。同时
* 子类都需要修改。
* 解决方法:使用装饰者模式
* @author Administrator
*
*/
9. 代码清单
package com.one.design;
public class Decorator {
}
/**
* 组件接口:动物
* @author Administrator
*
*/
interface Animal{
/**
* 吃的功能
*/
public void eat();
}
/**
* 组件实现类接口:猫
* @author Administrator
*
*/
class Cat implements Animal{
/**
* 吃的功能
*/
public void eat() {
System.out.println("Cat eat food");
}
}
/**
* 组件实现类接口:狗
* @author Administrator
*
*/
class Dog implements Animal{
/**
* 吃的功能
*/
public void eat() {
System.out.println("Dog eat food");
}
}
abstract class AnimalDecorator implements Animal{
public Animal animal;
public AnimalDecorator(Animal animal) {
this.animal = animal;
}
}
class Run extends AnimalDecorator{
public Run(Animal animal) {
super(animal);
}
/**
* 吃的功能
*/
public void eat() {
animal.eat();
run(animal);
}
public void run(Animal animal) {
System.out.println(animal+"run");
}
}
class Test {
public static void main(String[] args) {
Animal animal = new Run(new Cat() );
animal.eat();
Animal animal2 = new Run(new Dog() );
animal2.eat();
}
}