spring学习笔记3,设计模式----代理模式(静态)

设计模式-----代理模式

代理模式理解模型
在这里插入图片描述

代码实现----通过房屋出租,中介作为代理来理解程序

1.接口

//租房接口
public interface Rent {
    
    
    public void rent();//出租房屋
}

2.真实角色

//房东,真实的房东
public class Host implements Rent {
    
    
    public void rent() {
    
    
        System.out.println("我是房东,我要出租房子");
    }
}

3.代理角色

//中介,代理房东的房子,房东只管出租,其他都是代理来控制
public class Proxy  implements Rent{
    
    

    private Host host;//使用组合
    //组合动态的创建房东对象,代理直接通过房东对象来替房东租房。

    public Proxy(){
    
    

    }

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

    //实现租房接口
    public void rent() {
    
    
        showHouse();
        host.rent();//代理帮房东租房
        getMoney();
        heTong();
    }

    //看房
    public void showHouse(){
    
    
        System.out.println("房东很忙,委托中介带你看房。");

    }

    //收中介费
    public void getMoney(){
    
    
        System.out.println("中介收中介费");
    }

    //签租赁合同
    public void heTong(){
    
    
        System.out.println("中介和你签租赁合同");
    }

}

4.客户访问代理角色

//我,客户
public class Client {
    
    
    public static void main(String[] args) {
    
    
      //1.没有使用代理模式
        /*
        Host host=new Host();//产生一个房东,调用方法的出租房子的方法
        host.rent();
        */


        //2.使用了代理模式
        Host host=new Host();
        Proxy proxy = new Proxy(host);//把房东传给代理
        proxy.rent();

    }
}

代理模式的好处:
1.可以让真实角色的操作更加简单纯粹,不用去关注一些公共的业务。
2.公共也就交给代理角色,实现业务的分工。
3.公共业务发送扩展的时候,方便几种管理。

缺点:
1.一个真实角色就会产生一个代理角色,代码量对加倍。

猜你喜欢

转载自blog.csdn.net/weixin_45263852/article/details/113868916