SDayUp
做自已喜欢的事情就不是浪费时间。

设计模式是很重要的,在阅读一些框架的源码的时候,经常会看到设计模式的存在

本文来说一下委派模式(Delegate),委派模式不属于23种设计模式的。

写本文的原因是因为我最近在看Spring的源码,在读源码的过程中发现了好多的地方都在使用委派模式,就写下这篇文章做为笔记。

委派模式的作用就是调用和分配任务,它和代理模式有点像,但是代理模式注重过程,委派模式更加注重结果。

可以举一个在现实生活中你喜欢就好遇到的例子:在一家公司中,Boos向Leader下过任务,通过Leader将任务发配给了下面的员工,而在这里Leader就起到了任务的分配和调用。

我这里写了一个小例子来看下UML类图

员工接口,这里规定了员工类里面的方法

public interface IEmployee {
    public void exec(String doing);
}

这个是Leader类,这个里面只负责调用任务

public class Leader implements IEmployee {

    private Map<String,IEmployee> targets = new HashMap<>();

    public Leader(){
        targets.put("报表",new EmployeeA());
        targets.put("财会",new EmployeeB());
    }

    @Override
    public void exec(String doing) {
        targets.get(doing).exec(doing);
    }
}

两个员工类

public class EmployeeA implements IEmployee {
    @Override
    public void exec(String doing) {
        System.out.println("员工A正在做:" + doing + "事情");
    }
}

public class EmployeeB implements IEmployee {
    @Override
    public void exec(String doing) {
        System.out.println("员工B正在做:" + doing + "事情");
    }
}

Boss类里面只对Leader下达任务

public class Boss {
    public void command(String doing,Leader leader){
        leader.exec(doing);
    }
}

Test类

public class Test {
    public static void main(String[] args) {
        new Boss().command("报表",new Leader());
    }
}

委派模式了解以后,我写代码的时候要常用设计模式。

posted on 2020-07-05 17:44  SDayUp  阅读(202)  评论(0编辑  收藏  举报