• java设计模式~装饰器模式


    装饰器,顾名思义,就是把一个对象的功能进行扩展,添加新的装饰,让它具有新的特性和功能,在实现生活中,有很多装饰器实现的例子,比如人类可以跑,但有一个超人它不仅可以跑,而且还可以飞,这时在不改变原对象基础上,需要为超人添加飞的动作,就可以使用装饰模式。

    抽象组件

    /**
     * 人类.
     */
    public abstract class Human {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void run() {
            System.out.println("人类跑起来");
        }
    }
    
    

    具体组件

    
    /**
     * 超人.
     */
    public class SuperMan extends Human {
        private String food;
        private String work;
    
        public SuperMan(String food, String work) {
            this.food = food;
            this.work = work;
        }
    }
    
    

    抽象装饰器

    
    /**
     * 飞行装饰器.
     */
    public abstract class FlyDecorator extends Human {
        protected abstract void fly();
    
        private Human human;
    
        public FlyDecorator(Human human) {
            this.human = human;
        }
    
        @Override
        public void run() {
            if (human != null) {
                human.run();
            }
            fly();
        }
    }
    
    

    超人的装饰器

    /**
     * 超人的飞机装饰器.
     */
    public class SuperManFlyDecorator extends FlyDecorator {
        public SuperManFlyDecorator(Human human) {
            super(human);
        }
    
        @Override
        protected void fly() {
            System.out.println("超人会飞");
        }
    }
    
    

    让它飞起来

      Human human = new SuperMan("超人", "飞起来");
            FlyDecorator flyDecorator = new SuperManFlyDecorator(human);
            flyDecorator.run();
    
  • 相关阅读:
    假脱机技术
    HTTP报文
    字符串转换成浮点数的方法
    表变量与临时表空间
    规范浮点数
    什么是批处理
    浅谈性能测试、压力测试和负载测试
    关于CSDN的一个安全漏洞
    HttpWatch7.0测试工具
    vbscript能做什么
  • 原文地址:https://www.cnblogs.com/lori/p/11774007.html
Copyright © 2020-2023  润新知