GoF总结-10(装饰器模式)

1. 概念

指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

2. 优点

  1. 装饰器是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用。
  2. 通过使用不同装饰类及这些装饰类的排列组合,可以实现不同效果
  3. 装饰器模式完全遵守开闭原则

3. 缺点

装饰器模式会增加许多子类,过度使用会增加程序的复杂性。

4. 结构与实现

通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关系来创建一个包装对象(即装饰对象),并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰器模式的目标。

4.1 结构

主要角色:

  1. 抽象构件角色:定义一个抽象接口以规范准备接受附加责任的对象。
  2. 具体构件角色:实现抽象构件角色为其添加一些职责。
  3. 抽象装饰角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
    在这里插入图片描述

4.2 实现

//抽象构件角色
public interface Component {
    void operation();
}
//抽象装饰角色
public abstract class Decorator implements Component {

    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}
//具体构件角色 床
public class Bed implements Component{

    @Override
    public void operation() {
        System.out.println("我是一个用来睡觉的床");
    }
}
//具体装饰器 放枕头
public class Pillow extends Decorator {
    public Pillow(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunction();
    }

    private void addedFunction() {
        System.out.println("放上枕头");
    }
}
//具体装饰器 放被子
public class Quilt extends Decorator {
    public Quilt(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunction();
    }

    private void addedFunction() {
        System.out.println("放上被子");
    }
}

测试

public class DecoratorTest {
    @Test
    public void test1() {
        Bed newBed = new Bed();
        //在床上放枕头
        Pillow pillow = new Pillow(newBed);
        pillow.operation();
        //在床上放被子
        Quilt quilt = new Quilt(newBed);
        quilt.operation();
        //在床上放上枕头和被子
        Pillow pillowQuit1 = new Pillow(newBed);
        Quilt pillowQuit2 = new Quilt(pillowQuit1);
        pillowQuit2.operation();
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值