特点

要和代理模式区分开,仅仅持有被委托人的引用,只关心结果,不关心过程,不会改动过程。

代码示例

package com.delegate;

public interface IExecutor {
    void doing();
}
package com.delegate;

public class ExecutorA implements IExecutor {
    @Override
    public void doing() {
        System.out.println("A执行任务....");
    }
}
package com.delegate;

public class ExecutorB implements IExecutor {
    @Override
    public void doing() {
        System.out.println("B执行任务...");
    }
}
package com.delegate;

public class Dispatcher implements IExecutor {
    private IExecutor executor;

    public Dispatcher(IExecutor executor) {
        this.executor = executor;
    }

    @Override
    public void doing() {
        this.executor.doing();
    }
}
package com.delegate;

public class UnitTest {
    public static void main(String[] args) {
        Dispatcher dispatcher = new Dispatcher(new ExecutorB());
        dispatcher.doing();
    }
}