zoukankan      html  css  js  c++  java
  • 设计模式之 装饰者模式

    装饰者模式指在无须改变原有类及类的关系的情况下,动态扩展一个类的功能。它通过装饰者来包裹真实的对象,并动态地向对象添加或者撤销功能。

    image

    (1)定义Sourceable接口

    public interface Sourceable{
        public void createComputer();
    }

    (2)定义Sourceable接口的实现类

    public class Source implements Sourceable{
        private final static Log logger = LogFactory.getLog(Source.class);
        @Override
        public void createComputer(){
            logger.info("create computer by Source");
        }
    }

    (3)定义装饰者类

    public class Decorator implements Sourceable{
        private final static Log logger = LogFactory.getLog(Decorator.class);
    
        private Sourceable source;
        public Decorator(Sourceable source){
            super();
            this.source = source;
        }
    
        @Override
        public void createComputer(){
            source.createComputer();
            logger.info("make system");
        }
    }

    Decorator扩展了原来的source的功能

    (4)使用

    public static void main(String[] args){
        Sourceable source = new Source();
        Sourceable obj = new Decorator(source);
        obj.createComputer();
    }

  • 相关阅读:
    Pandas学习笔记,如何从DataFrame里选择一个Series
    数据结构_郝斌_数组
    数据结构_郝斌_预备知识2
    数据结构_郝斌_预备知识1
    数据结构_郝斌_目录
    数据结构_郝斌_链表
    Vocabulary Recitation 2020/04/08
    5月11号
    5月10号
    5月9号
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15229475.html
Copyright © 2011-2022 走看看