JAVA的代理模式

 
代理模式:为其他对象提供一种代理以控制对这个对象的访问.说白了就是,在一些情况下客户不想或不能直接引一个对象,而代理对象可以在客户和目标对象之间起到中介作用.去掉客户不能看到的内容和服务或都增添客户需要的额外服务.
给大家举个比较简单的例子:
假如你买台IBM的笔记本,IBM产家是不提供鼠标的.但是我们如果从代理商的手里买就有鼠标和送.
很简单的例子,写几个类来实现一下吧.
首先设计一个购买的接口代码如下:(ComputerInterface.java)
package test.lyx;
public interface ComputerInterface {
    public void buy();
}
建一个电脑类实现购买的接口代码如下:(Computer.java)
package test.lyx;
public class Computer implements ComputerInterface{
    private String pcName = "IBMT60" ;
    private int pcPrice =17800;
    public String getPcName() {
        return pcName ;
    }
    public void setPcName(String pcName) {
        this . pcName = pcName;
    }
    public int getPcPrice() {
        return pcPrice ;
    }
    public void setPcPrice( int pcPrice) {
        this . pcPrice = pcPrice;
    }
    public void buy() {
    System. out .print( " 获得笔记本电脑: " + pcName + " 一台 " );
    }
}
再建设一个代理商的类:用来完成买电脑和赠送鼠标:( ComputerProxy.java
package test.lyx;
public class ComputerProxy {
    private ComputerInterface pci ;
    public ComputerInterface getPci() {
        return pci ;
    }
    public void setPci(ComputerInterface pci) {
        this . pci = pci;
    }
    public void buy(){
        pci .buy();
        System. out .println( " 赠送鼠标一个 " );
    }
}
建一个主函数测试一下吧:( TestDemo.java
package test.lyx;
public class TestDemo {
    public static void main(String[] args) {
        ComputerProxy c1= new ComputerProxy();
        c1.setPci( new Computer());
        c1.buy();
    }
}
运行结果如下:
获得笔记本电脑: IBMT60 一台获得鼠标一个
以上就是代理功能的实现,由代理商销售笔记本,并赠送鼠标.但是这样的程序只适合是销售IBM笔记本.那么如果要是其它品牌呢.所以我们来更改一个代理类.来实现动态的代理.
建立一个类代码如下:( ComputerProxy2 java
package test.lyx;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ComputerProxy2 implements InvocationHandler{
    private Object delegate ;
    // 描述是谁的代理,也就是与那个类有关系
    public Object bind(Object delegate){
        this . delegate =delegate;
        return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this );
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
           System. out .println( " 赠送鼠标一个! " );
       Object result=method.invoke( delegate , args);
       return result;
    }
}
然后在主函数中加上:
        ComputerProxy2 c2= new ComputerProxy2();
        ComputerInterface ci2=(ComputerInterface)c2.bind( new Computer());
        ci2.buy();
就可以实现动态代理了.
 
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值