静态代理模式

首先通过一张图了解一下代理模式
在这里插入图片描述
在这里:中介就是一个代理人,帮助房东实现出租房屋的功能,这就是静态代理的实现。

然后看代码

房东类
package com.xiaobai.proxy;

/**
 *  房东 出租角色
 */
public class Landlord implements Rent{
    @Override
    public void rent() {
        System.out.println("我是房东 我房屋租出");
    }
}
代理类 房屋中介
package com.xiaobai.proxy;

/**
 *  代理角色 房屋中介
 */
public class HousingAgency implements Rent{

    private Rent rent;

    public HousingAgency() {

    }

    public HousingAgency(Rent rent) {
        this.rent = rent;
    }

    @Override
    public void rent() {
        // 看房
        see();
        // 合同
        contract();
        // 收费
        pay();
        // 转交房租
        give();
        // 成功租房
        rent.rent();
    }

    /**
     * 看房
     * @return boolean
     */
    private boolean see(){
        System.out.println("中介带房客看房,房客觉得可以,就租房,不可以就拜拜");
        return true;
    }

    /**
     * 签合同
     * @return boolean
     */
    private boolean contract(){
        System.out.println("签合同,如果没有霸王条款则正常签订");
        return true;
    }

    /**
     * 交钱
     * @return boolean
     */
    private boolean pay(){
        System.out.println("签订完合同交房租");
        return true;
    }

    /**
     * 中介将房租转给房东
     * @return 返回一张收据
     */
    private String give(){
        System.out.println("转交房租给房东");
        return "房东已收到钱";
    }
}
房东和中介都要完成的动作——租房
package com.xiaobai.proxy;

public interface Rent {
    // 出租房屋方法
    public void rent();
}
来租房的客户
package com.xiaobai.proxy;

/**
 * 房客 承租角色
 */
public class Tenant {
    public static void main(String[] args) {
        // 创建真实的房东对象
        Landlord landlord = new Landlord();
        // 创建代理对象并代理房东出租
        HousingAgency housingAgency = new HousingAgency(landlord);
        // 将房屋出租
        housingAgency.rent();
    }
}
运行结果

在这里插入图片描述

静态代理模式优点:
  1. 分解角色功能,使真实角色(房东)更加纯粹
  2. 真正的租房是由中介完成的,使业务集中在中介类,业务更加纯粹
  3. 中介可以帮助房东完成各项事务,便于扩展业务,而且业务发生改变时便于集中管理
缺点:
  1. 每有一个角色就要有一个代理,代码量翻倍且大多冗余
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值