静态代理模式:为其他对象提供一种代理以达控制这个对象的目的。代理说白了就是“真实角色"的代表,在访问对象时引入一定的间接性,因为间接性可以在不改变原对象的情况下横向附加很多其他功能。
代码实现:
public class Proxy {
public static void main(String[] args) {
ProxyPeople proxy = new ProxyPeople(new Host());
proxy.rent();
}
}
/**
* 静态代理模式:为其他对象提供一种代理以达控制这个对象的目的
* 代理说白了就是“真实角色"的代表,在访问对象时引入一定的间接性,因为间接性可以在不改变原对象的情况下横向附加很多其他功能
*/
//行为:租房
interface Rent{
public void rent();
}
//房东,被代理的对象
class Host implements Rent{
public void rent(){
System.out.println("房东要出租房子。");
}
}
//中介,代理人
class ProxyPeople implements Rent{
//代理对象是房东
private Host host;
public ProxyPeople(){}
public ProxyPeople(Host host){
this.host = host;
}
//代理类的具体实现
public void rent(){
seeHouse();
host.rent();
hetong();
fare();
}
public void seeHouse(){
System.out.println("中介带你看房子");
}
public void fare(){
System.out.println("中介要收中介费");
}
public void hetong(){
System.out.println("签约租赁合约");
}
}
测试结果: