本帖最后由 侯国奇 于 2013-3-26 15:18 编辑
代理类就是为其他对象提供一种代理,以控制被代理对象的访问。
可以从下面的例子中得出结论:
Subject.java- package com.archer.proxy;
- public interface Subject {
- public void findFriend();//找朋友
- }
复制代码 CompanyProxy.java- package com.archer.proxy;
- public class CompanyProxy implements Subject {
- private Subject proxy;
-
- CompanyProxy(Subject proxy) {
- this.proxy = proxy;
- }
-
- public void start() {
- System.out.println("根据客户要求查找合适的朋友");
- System.out.println("相互联系,确定约会的时间地点");
- }
- public void end() {
- System.out.println("约会结束");
- }
- public void findFriend() {
- start();
- proxy.findFriend();
- end();
- }
- }
复制代码 Person.java- package com.archer.proxy;
- class Person implements Subject {
- private String name;
- Person(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public void findFriend() {
- System.out.println(name+"开始约会");
- System.out.println("相互介绍");
- System.out.println("聊天吃饭");
- System.out.println("散步");
- System.out.println("看电影");
- System.out.println("吃夜宵");
- System.out.println("送对方回家,约下次再见");
- }
- }
复制代码 Test.java- package com.archer.proxy;
- public class Test {
- public static void main(String[] args) {
- Subject p = new Person("张三");
- CompanyProxy cp = new CompanyProxy(p);
- cp.findFriend();
- }
- }
复制代码 |
|