程序员社区

静态代理模式

角色分析:

  • 抽象角色:一般使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作
  • 客户:访问代理对象的人
    在这里插入图片描述

租房(接口)

public interface Rent {
    void rent();
}

房东(真实角色)

public class Host implements Rent{
    public void rent() {
        System.out.println("房东要出租房子");
    }
}

代理(代理角色)

package com.kuang.domain;

public class Proxy implements Rent {
    private Host host;
	
    public Proxy(Host host){
        this.host=host;
    }
	
	//租房
    public void rent(){
        host.rent();
    }

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

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

4.客户(测试类)

public class Client {
    public static void main(String[] args) {
        Proxy proxy = new Proxy(new Host());
        proxy.rent();
        proxy.seeHost();
        proxy.fare();
    }
}

代理对象可以在被代理对象的基础上增加额外的功能
代理对象和被代理对象都要是实现相同的接口
弊端:一个被代理角色就要对应一个代理角色

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 静态代理模式

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区