代理模式
之前也有写过一些博客,但是每每都是从基层开始写,然后又坚持不下去,目前下定决心好好写写博客,本人也是一个菜鸟,如有写错的地方望指正,共同学习与进步!
代理模式的结构
代理人和被代理人都要继承的接口
他们需要处理同样的事情
package proxy;
/**
* 定义人的接口
* @author Luo
*
*/
public interface Person {
/**
* 吃饭的方法
*/
void eat();
}
被代理人实例
package proxy;
public class PersonC implements Person {
public void eat() {
System.out.println("我去吃饭");
}
}
代理人实例
package proxy;
/**
* @author Luo
*
*/
public class PersonB implements Person {
private boolean isFriend;
private Person person;
public PersonB(Person person) {
this.person = person;
}
public PersonB(boolean isFriend, Person person) {
this.isFriend = isFriend;
this.person = person;
}
/**
* 吃饭方法
*/
public void eat() {
if (isFriend) {
person.eat();
} else {
System.out.println("C不去吃饭");
}
}
}
测试代码
package proxy;
public class ProxyTest {
public static void main(String[] args) {
PersonC c = new PersonC();
PersonB b = new PersonB(false, c);
b.eat();
}
}
结果
C不去吃饭
总结
当你需要某个对象满足某种情况才去使用它,并且原类不发生改变的时候,这个时候你就可以使用代理模式去处理了。