java 动态代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 代理的接口
public interface ManToolsFactory {
void saleManTools(String size);
}


public class AaFactory implements ManToolsFactory {
@Override
public void saleManTools(String size) {
System.out.println("按需求定制了一个size为"+size+"的model");
}
}

// 代理类
public class MarkCompany implements InvocationHandler {

/*持有的真实对象*/
private Object factory;

public Object getFactory() {
return factory;
}

public void setFactory(Object factory) {
this.factory = factory;
}

/*通过Proxy获得动态代理对象*/
public Object getProxyInstance(){
return Proxy.newProxyInstance(factory.getClass().getClassLoader(),
factory.getClass().getInterfaces(),this);
}

/*通过动态代理对象方法进行增强*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {


Object result = method.invoke(factory, args);
return result;
}


public class Client {

public static void main(String[] args) {
/*动态代理模式---------------*/
ManToolsFactory aafactory = new AaFactory();
MarkCompany markCompany = new MarkCompany();

markCompany.setFactory(aafactory);
ManToolsFactory employee1
= (ManToolsFactory)markCompany.getProxyInstance();
employee1.saleManTools("E");
}
}
1
2


文章目录
|