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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86 |
/** * */ package
typeinfo; /** * 简单代理模式的使用。 * 代理模式提供了隐藏和扩展的能力,将被代理者可以隐藏起来,而且可以在代理类中对被代理的 * 功能再进行加工包装,使其更丰满。 * */ /** * 定义出代理对象的接口 * @author LYL * */ interface
Interface{ void
doSomething(); void
somethingElse(String arg); } /** * 被代理的对象,是真正干活的 * @author LYL * */ class
RealObject implements
Interface{ @Override public
void doSomething() { System.out.println( "RealObject doSomething" ); } @Override public
void somethingElse(String arg) { System.out.println( "RealObject somethingElse" +arg); } } /** * 代理类,同样实现了Interface接口,但是只是一个代理,真正干活是另有其人。 * 代理类只是起到一个中间角色,起到白手套的作用。 * @author LYL * */ class
SimpleProxy implements
Interface { private
Interface proxied; //被代理者 public
SimpleProxy(Interface proxied){ this .proxied=proxied; } @Override public
void doSomething() { //除了代理以外,还可以附加一些其它的服务 System.out.println( "SimpleProxyDemo doSomething." ); //将工作转给被代理的来做 this .proxied.doSomething(); } @Override public
void somethingElse(String arg) { System.out.println( "SimpleProxyDemo somethingElse " +arg); this .proxied.somethingElse(arg); } } /** * 简单代理类测试 * @author LYL * */ public
class SimpleProxyDemo{ public
static void consumer(Interface iface){ iface.doSomething(); iface.somethingElse( " invoke " ); } public
static void main(String args[]) throws
Exception{ //直接使用类 System.out.println( "直接使用类" ); consumer( new
RealObject()); //通过代理来使用被代理的类 System.out.println( "通过代理来使用被代理的类" ); consumer( new
SimpleProxy( new
RealObject())); } } |
原文:http://www.cnblogs.com/bjwylpx/p/3675350.html