zoukankan      html  css  js  c++  java
  • 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();
    
  • 相关阅读:
    低功耗计算机视觉技术前沿,四大方向,追求更小、更快、更高效
    ELECTRA中文预训练模型开源,性能依旧媲美BERT
    局部敏感哈希源代码-python
    利用局部敏感哈希改进推荐系统实时性
    局部敏感哈希算法介绍
    为什么要用局部敏感哈希
    多采用panda的数据处理方式
    delphi:文件操作
    delphi:常用函数
    delphi:打印日志
  • 原文地址:https://www.cnblogs.com/lori/p/11774007.html
Copyright © 2011-2022 走看看