08 设计模式 静态代理

时间:2022-07-22
本文章向大家介绍08 设计模式 静态代理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

静态代理

例如:在租房时候,不需要直接去找房东,只要去找中介,中介会将房子租给我们,而我们不必和房东接触,便可以租下来房子

首先创建一个接口,代表租房这个事情

public interface Rent {
    public void rent();
}

然后再创建一个类代表房东,实现了租房这个接口

public class Landlord implements Rent{
    @Override
    public void rent() {
        System.out.println("出租房屋");
    }
}

在没有中介的时候,房东需要自己和我们打交道

public static void main(String[] args) {
    Landlord landlord = new Landlord();
    landlord.rent();
}

这时,房东觉得很麻烦,于是就找了个房屋中介

public class Agent implements Rent{

    Landlord landlord;

    Agent(Landlord landlord){
        this.landlord = landlord;
    }

    @Override
    public void rent() {
        clean();
        contract();
        landlord.rent();
        fare();
    }

    public void clean(){
        System.out.println("打扫房屋");
    }

    public void contract(){
        System.out.println("签订合同");
    }

    public void fare(){
        System.out.println("收租");
    }

}

这样有了中介之后,房东不需要操心租房这件事了,中介在其中做了一些处理,最后将房屋租给我们,这就是一个典型的静态代理