设计模式(十二)——代理模式(Proxy)
在直接访问对象时带来的问题,比如说:要访问的对象在远程的机器上。在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层。
实现
顾客要租房,房东要出租房子,
Landlord.java 房东要出租房子。】
public class Landlord {
public void rent() {
System.out.println("房东要出租房子!");
}
}
Customera.java 顾客要租房,那么只需要创建一个房东类,调用房东类的租房方法即可。
public class Customer {
public static void main(String[] args) {
Landlord landlord = new Landlord();
landlord.rent();
}
}
使用代理模式,把租房这个抽象角色剥离出来,现在顾客租房不去找房东,而是找中介,在这过程中,中介会有附属操作。
抽象角色:租房
//抽象角色:租房
public interface Lease {
public void rent();
}
真实角色: 房东,房东要出租房子
//真实角色: 房东,房东要出租房子
public class Landlord implements Lease {
public void rent() {
System.out.println("房东要出租房子!");
}
}
代理角色:中介,代理房东把房子租出去
//代理角色,中介
public class Intermediary implements Lease{
private Landlord landlord;
public Intermediary(Landlord landlord) {
this.landlord = landlord;
}
public void rent() {
this.landlord.rent();
kanfang();
hetong();
shouqian();
}
public void kanfang() {
System.out.println("中介:看房");
}
public void hetong(){
System.out.println("中介:签合同");
}
public void shouqian() {
System.out.println("中介:收钱");
}
}
顾客:去租房子
//顾客
public class Customer {
public static void main(String[] args) {
Intermediary intermediary = new Intermediary(new Landlord());
intermediary.rent();
}
}
现在顾客要租房子,直接去找中介,中介会代理房东把房子租出去,同时,中介会有附属操作。