java如何实现委托
委托模式的基本概念
委托(Delegate)是一种设计模式,允许对象将部分职责交给其他对象处理。Java中可以通过接口或函数式编程(如Lambda表达式)实现类似功能。
使用接口实现委托
定义一个接口,包含需要委托的方法,具体实现由其他类完成。
// 定义委托接口
interface Task {
void execute();
}
// 实现委托的具体类
class ConcreteTask implements Task {
@Override
public void execute() {
System.out.println("具体任务被执行");
}
}
// 委托调用方
class Delegator {
private Task task;
public Delegator(Task task) {
this.task = task;
}
public void doWork() {
task.execute();
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Task task = new ConcreteTask();
Delegator delegator = new Delegator(task);
delegator.doWork();
}
}
使用Lambda表达式简化
Java 8+支持函数式接口,可通过Lambda实现更简洁的委托。
// 函数式接口(单一抽象方法)
@FunctionalInterface
interface Operation {
int calculate(int a, int b);
}
// 使用Lambda传递行为
public class Main {
public static void main(String[] args) {
Operation add = (a, b) -> a + b;
Operation multiply = (a, b) -> a * b;
System.out.println(add.calculate(5, 3)); // 输出8
System.out.println(multiply.calculate(5, 3)); // 输出15
}
}
动态代理实现高级委托
通过java.lang.reflect.Proxy动态创建代理对象,拦截方法调用并委托给其他逻辑。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 目标接口
interface Service {
void serve();
}
// 实际实现类
class RealService implements Service {
@Override
public void serve() {
System.out.println("实际服务执行");
}
}
// 动态代理处理器
class DelegationHandler implements InvocationHandler {
private Object target;
public DelegationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("委托前逻辑");
Object result = method.invoke(target, args);
System.out.println("委托后逻辑");
return result;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Service realService = new RealService();
Service proxy = (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class[]{Service.class},
new DelegationHandler(realService)
);
proxy.serve(); // 输出委托前后的日志
}
}
关键点总结
- 接口委托:通过接口定义行为,具体实现可灵活替换。
- Lambda简化:适用于函数式接口,减少样板代码。
- 动态代理:适合需要拦截或增强方法的场景,如AOP。






