首页 > 应用开发 > Java > java学习之代理模式
|
1
2
3
4
5
6
7
8
9
10
11
12
|
package com.invicme.apps.aop.proxy;
/**
*
* @author lucl
*
* 抽象角色
*
*/
public interface IDoSomeThing {
public void doSomeThing ();
}
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.invicme.apps.aop.proxy;
/**
*
* @author lucl
*
* 真实角色
*
*/
public class DoSomeThing implements IDoSomeThing {
@Override
public void doSomeThing() {
System.out.println("I'm doing some thing...");
}
}
|
|
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
|
package com.invicme.apps.aop.proxy;
/**
*
* @author lucl
*
* 代理类
*
*/
public class DoSomeThingProxy implements IDoSomeThing {
private IDoSomeThing iDoSomeThing;
private String userName;
public DoSomeThingProxy (IDoSomeThing iDoSomeThing, String userName) {
this.iDoSomeThing = iDoSomeThing;
this.userName = userName;
}
@Override
public void doSomeThing() {
// 调用目标对象之前可以做相关操作(如记录日志、根据用户判断是否能够进行doSomeThing的操作)
System.out.println("Current user " + userName + " want to do some thing.");
this.iDoSomeThing.doSomeThing();
// 调用目标对象之后可以做相关操作
System.out.println("Current user " + userName + " do some thing end.");
}
}
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.invicme.apps.aop.proxy;
/**
*
* @author lucl
*
* 驱动类,希望执行某些业务逻辑
*
*/
public class MainDriver {
public static void main(String[] args) {
IDoSomeThing iDoSomeThing = new DoSomeThing();
IDoSomeThing doSomeThingProxy = new DoSomeThingProxy(iDoSomeThing, "张三");
doSomeThingProxy.doSomeThing();
doSomeThingProxy = new DoSomeThingProxy(iDoSomeThing, "李四");
doSomeThingProxy.doSomeThing();
}
}
|
InvocationHandler handler = new MyInvocationHandler(...);
Class proxyClass = Proxy.getProxyClass(
Foo.class.getClassLoader(), new Class[] { Foo.class });
Foo f = (Foo) proxyClass.
getConstructor(new Class[] { InvocationHandler.class }).
newInstance(new Object[] { handler });
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29917475/viewspace-2121569/ ,如需转载,请注明出处,否则将追究法律责任。