zoukankan      html  css  js  c++  java
  • 回顾装饰模式

    最近面试经常被问到这两种设计模式的区别,小编觉得也没什么可比较的地方。额……可能是站的角度不一样吧,那就来比较一下。



    说到装饰模式,首先想到的是牛奶加糖加奶的故事。使用装饰模式,可以灵活的解决不同客户的多种附加需求。比如:只加糖、只加奶、又加糖又加奶。


    而代理模式,你应该会想到动态代理之类的,是代理对象的行为。

    那么装饰模式如何实现动态添加类的职责呢?

    概括来说,就是通过继承。来看一下类图:

    1、ConcreteComponent被装饰者和Decorator装饰者同时实现(继承)Component接口(抽象类)。

    2、并且,Decorator中持有Component的引用。

    3、Decorator的两个子类,具体装饰者分别有不同的装饰作用,比如加糖、加奶。
    这里写图片描述

    下面是代码中的体现:

    public abstract class Component {
    
        abstract void test();
    }
    
    //被装饰对象
    public class ConcreteComponent extends Component {
        public void test(){
            System.out.println("Compont的原有方法");
        }
    }
    
    //装饰类
    public class Decorator extends Component {
    
        //定义私有变量Component
        private Component component;
    
        //在构造函数中传入
        public Decorator(Component component){
            this.component=component;
        }
        @Override
        void test() {
            if(component!=null){
                component.test();
            }
    
        }
    
    }
    
    //具体装饰类
    public class ConcreteDecoratorA extends Decorator{
    
        public ConcreteDecoratorA(Component component){
            super(component);
        }
    
        @Override
        void test() {
    
            super.test();
            System.out.println("add sugar");
        }
    
    
    }
    
    //简单调用
        ConcreteComponent component=new ConcreteComponent();
            ConcreteDecoratorA decoratorA=new ConcreteDecoratorA(component);
            ConcreteDecoratorB decoratorB=new ConcreteDecoratorB(component);
            decoratorA.test();
            //decoratorB.test();

    代码中只是简单的实现,具体业务中还有很多变种,比如java中IO就用到了装饰模式,理解最重要。

  • 相关阅读:
    操作系统原理5——文件管理
    Hadoop worldcount
    Java Future源码分析
    HBase入门教程
    Java自定义cas操作
    dubbo客户端源码分析(一)
    log4j2配置文件
    paxos协议
    Guava限流工具RateLimiter使用
    jvm内置锁synchronized不能被中断
  • 原文地址:https://www.cnblogs.com/saixing/p/6730198.html
Copyright © 2011-2022 走看看