zoukankan      html  css  js  c++  java
  • java23种设计模式-结构型模式-装饰者模式

    一、定义

    装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

    这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

    二、优点及缺点

    优点:

    1、装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

    缺点:

    1、多层装饰比较复杂,太多装饰者会很乱。

    三、代码实现:

    现在又个图形接口和两个实现类:

    接口:

    /**
     *  @author: wsq
     *  @Date: 2020/9/25 18:11
     *  @Description: 图形抽象类
     */
    public interface Shape {
        public void draw();
    }

    实现类:

    /**
     *  @author: wsq
     *  @Date: 2020/9/25 18:12
     *  @Description: 圆形类
     */
    public class Circle implements Shape{
        @Override
        public void draw() {
            System.out.println("I am drawing Circle!!!");
        }
    }
    /**
     *  @author: wsq
     *  @Date: 2020/9/25 18:11
     *  @Description: 直线
     */
    public class Line implements Shape{
        @Override
        public void draw() {
            System.out.println("I am drawing a line!");
        }
    }

    现在需要再draw之前,画一个颜色,就用到了装饰者模式

    装饰者类:

    /**
     *  @author: wsq
     *  @Date: 2020/9/25 18:14
     *  @Description: 装饰者类
     */
    public class Decorator implements Shape{
        private Shape shape;
        public Decorator(Shape shape){
            this.shape = shape;
        }
        @Override
        public void draw() {
            this.shape.draw();
            System.out.println("I am add color to this shape!!!");
        }
    }

    测试类:

    /**
     *  @author: wsq
     *  @Date: 2020/9/25 18:14
     *  @Description: 装饰者类
     */
    public class Decorator implements Shape{
        private Shape shape;
        public Decorator(Shape shape){
            this.shape = shape;
        }
        @Override
        public void draw() {
            this.shape.draw();
            System.out.println("I am add color to this shape!!!");
        }
    }

    四、源码级别

    BufferedInputStream和DataInputStream继承了InputStream,是它的装饰类,大家可以追一下源码,是对它功能的增强。

    五、总结

    使用场景: 1、扩展一个类的功能。

    注意事项:可代替继承。

  • 相关阅读:
    ping
    android Handler总结
    配置网络测试环境的批处理
    shell 的选项解析
    [转] Linux 中共享库的搜索
    SecureCRT 脚本一则(0720.Rev.1)
    使用 Wget 完成自动 Web 认证(推 portal)
    shell 选项解析之需求一:多路径自动补全
    getopts 的简单模拟(09.12 Rev)
    ThinkPHP框架使用心得三 RBAC权限控制(2)简要原理
  • 原文地址:https://www.cnblogs.com/mcjhcnblogs/p/13731784.html
Copyright © 2011-2022 走看看