首页 > 其他 > 详细

简单代理模式

时间:2014-04-20 13:16:18      阅读:500      评论:0      收藏:0      [点我收藏+]
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()));
    }
}

 

简单代理模式,布布扣,bubuko.com

简单代理模式

原文:http://www.cnblogs.com/bjwylpx/p/3675350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!