# 23种设计模式-装饰器模式

# 1.装饰器模式

可以动态给对象添加一些额外的职责从而实现功能的拓展,在运行时选择不同的装饰器,从而实现不同的行为

# 优缺点

# 优点:

  1. 可维护性高
  2. 灵活性好
  3. 复用高
  4. 多样性

# 缺点:

  1. 使用装饰器模式时会产生很多细粒度的装饰器对象,这些装饰器对象由于接口和功能的多样化导致系统复杂度增加,功能越复杂,需要的细粒度对象越多
  2. 由于更大的灵活性,也就更容易出错,特别是对于多级装饰的场景,错误定位会更加繁琐

# 使用场景

# 实现方式

#

//定义被装饰者
interface Human
{
    void wearClothes();
}

//定时装饰者
abstract class Decorator implements Human
{
    private Human human;

    public Decorator(Human human)
    {
        this.human = human;
    }

    @Override
    public void wearClothes()
    {
        human.wearClothes();
    }
}

//下面定义三种装饰,这是第一个,第二个第三个功能依次细化,即装饰者的功能越来越多
class Decorator_zero extends Decorator {

    public Decorator_zero(Human human) {
        super(human);
    }

    public void goHome() {
        System.out.println("进房子。。");
    }

    @Override
    public void wearClothes() {
        super.wearClothes();
        goHome();
    }
}

class Decorator_first extends Decorator {

    public Decorator_first(Human human) {
        super(human);
    }

    public void goClothespress() {
        System.out.println("去衣柜找找看。。");
    }

    @Override
    public void wearClothes() {
        super.wearClothes();
        goClothespress();
    }
}

class Decorator_two extends Decorator {

    public Decorator_two(Human human) {
        super(human);
    }

    public void findClothes() {
        System.out.println("找到一件D&G。。");
    }

    @Override
    public void wearClothes() {
        super.wearClothes();
        findClothes();
    }
}


class Person implements Human {

    @Override
    public void wearClothes() {
        System.out.println("穿什么呢。。");
    }
}

//测试类
public class DecoratorTest
{
    public static void main(String[] args)
    {
        Human person = new Person();
        Decorator decorator = new Decorator_two(new Decorator_first(new Decorator_zero(person)));
        decorator.wearClothes();
    }
}

参考博客:https://blog.csdn.net/a745233700/article/details/83628903