概念
代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象。
代理模式用于解决两种问题:
1. 控制对基础对象的访问
2. 在访问时增加额外的功能
静态代理
要求被代理类和代理类同时实现相应的一套接口;
通过代理类的对象调用重写接口的方法时,实际上执行的是被代理类同样的方法的调用。
代码
package com.mulinhu.staticproxy;
public interface Person {
public void findLove();
}
package com.mulinhu.staticproxy;
public class Son implements Person {
public void findLove() {
System.out.println("儿子要求:身高要在160cm以上及肤白貌美");
}
}
package com.mulinhu.staticproxy;
/**
* 儿子工作忙,父亲帮儿子相亲
*/
public class Father implements Person {
private Son son;
public Father(Son son){
this.son=son;
}
public void findLove() {
System.out.println("父亲帮忙物色对象");
this.son.findLove();
System.out.println("双方同意,开始交往!");
}
}
package com.mulinhu.staticproxy;
//测试代码
public class Main {
public static void main(String[] args) {
Son son=new Son();
Father father=new Father(son);
father.findLove();
}
}