接口的应用:代理模式(Proxy)

 

 

 

应用场景:
 安全代理:屏蔽对真实角色的直接访问。
 远程代理:通过代理类处理远程方法调用(RMI)
 延迟加载:先加载轻量级的代理对象,真正需要再加载真实对象
比如你要开发一个大文档查看软件,大文档中有大的图片,有可能一个图片有
100MB,在打开文件时,不可能将所有的图片都显示出来,这样就可以使用代理
模式,当需要查看图片时,用proxy来进行大图片的打开。
分类:
 静态代理(静态定义代理类)
 动态代理(动态生成代理类)
 JDK自带的动态代理,需要反射等知识

 

实例1:

package com.ch.java1;
/*
 * 接口的应用:代理模式
 * 
 */
public class NetWorkTest {
    public static void main(String[] args) {
        Server server = new Server();
//        server.browse();
        ProxyServer proxyServer = new ProxyServer(server);
        
        proxyServer.browse();//只是调用了代理的browse方法
        
    }
}

interface NetWork{
    
    public void browse();
    
}

//被代理类
class Server implements NetWork{

    @Override
    public void browse() {
        System.out.println("真实的服务器访问网络");
    }

}
//代理类
class ProxyServer implements NetWork{
    
    private NetWork work;
    
    public ProxyServer(NetWork work){
        this.work = work;
    }
    

    public void check(){
        System.out.println("联网之前的检查工作");
    }
    
    @Override
    public void browse() {
        check();
        
        work.browse();
        
    }
    
}

 

 

 

 

实例2:

package com.ch.java1;


public class StaticProxyTest {

    public static void main(String[] args) {
        Proxy s = new Proxy(new RealStar());
        s.confer();
        s.signContract();
        s.bookTicket();
        s.sing();
        s.collectMoney();
    }
}

interface Star {
    void confer();// 面谈

    void signContract();// 签合同

    void bookTicket();// 订票

    void sing();// 唱歌

    void collectMoney();// 收钱
}
//被代理类 class RealStar implements Star { public void confer() { } public void signContract() { } public void bookTicket() { } public void sing() { System.out.println("明星:歌唱~~~");//只有明星自己才能唱歌 } public void collectMoney() { } }

//代理类 class Proxy implements Star { private Star real; public Proxy(Star real) { this.real = real; } public void confer() { System.out.println("经纪人面谈"); } public void signContract() { System.out.println("经纪人签合同"); } public void bookTicket() { System.out.println("经纪人订票"); } public void sing() { real.sing();//经纪人的sing方法real.sing();调用了被代理类star里的sing()方法 } public void collectMoney() { System.out.println("经纪人收钱"); } }

 

 

posted @ 2021-04-01 10:20  小白冲  阅读(364)  评论(0编辑  收藏  举报