java静态代理模式

通过模拟租房来展现静态代理模式

  • 租房接口
//租房
public interface Rent {
    public void rent();
}
  • 被代理的真实角色房东
//房东
public class Host implements Rent {

    @Override
    public void rent() {
        System.out.println("房东要出租房租");
    }
}
  • 代理角色
public class Proxy implements Rent {
    private Host  host;
    //这里最好是private Rent rent;因为Host实现了Rent接口,
    //添加构造方法,在客户端new Proxy时传入host,因为host实现了Rent接口(java的多态机制)
    /*public Proxy(Rent rent) {
        this.rent = rent;
    }*/

    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        fare();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }

    //合同
    public void hetong(){
        System.out.println("签租赁合同");
    }

    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}
  • 通过客户端访问
public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
//        host.rent();
        //代理
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

输出结果:
中介带你看房
房东要出租房租
签租赁合同
收中介费

posted @ 2024-04-18 15:32  文采杰出  阅读(2)  评论(0编辑  收藏  举报