java动态代理详解

本文章要用很土的语言描述Java动态代理,力求更易被理解。Java是JDK5中新加的机制,大家都知道Spring是用Java的动态代理实现的,那这个动态代理是什么东东呢,首先他肯定是个代理,我们先讲代理,把代理弄明白了,动态代理就好说了

代理都知道吧,你去买东西就有很多的代理商,他们就是卖原厂的东西。比如,你天天要买肉,猪是农民伯伯养的,但你是从屠夫手上买到肉的,这个屠夫就可以当成是代理。那为什么要代理呢,代理有什么用呢,当然是有事给他做了,对于屠夫这个代理就好理解了,因为你自己不可能去宰猪吧,所以代理就是去买活猪,然后宰掉再卖给你,当然屠夫有可能给肉注点水,关键看他坏不坏,所以屠夫的整个流程就是:

这个流程用代码怎么实现呢:我们应该要用三个类You、Butcher、Farmer分别指你、屠夫、农民伯伯。其中农民伯伯又提供一个买肉的方法给屠夫调用,这个方法输入是钱的数量,返回是肉的数量,都用int型,代码如下:

复制代码 代码如下:

class Farmer {
    public int buyMeat(int money) {
        int meat = 0;
        // ... meat = ***;
        return meat;
    }
}

而屠夫则提供一个买肉的方法给你调用,同样是输入钱,返回肉,但是会把肉加工一下(杀猪和刮猪毛在代码中就省了,要不然还得为猪写个类),代码如下:

复制代码 代码如下:

class Butcher {
    public int buyMeat(int money) {
        Farmer farmer = new Farmer();            // 1.find a farmer.
        int meat = farmer.buyMeat(money);        // 2.buy meat from the farmer.
        meat += 5;                               // 3.inject 5 pound water into the meat, so weight will increase.
        return meat;                             // 4.return to you.
    }
}

然你从屠夫手上买肉的代码就变成这样:

复制代码 代码如下:

class You {
    public void work() {
        int youMoney = 10;
        Butcher butcher = new Butcher();        // find a butcher.
        int meat = butcher.buyMeat(youMoney);
        System.out.println("Cook the meat, weight: " + meat);  // you cooked it. 
    }
}

这个程序我们还可以优化一下,我们发现屠夫有农民有一个相同的买肉方法,我们可以提取一个接口,叫为商贩(pedlar)吧,以后你买肉就不用管他是屠夫还是农民伯伯了,只要他有肉卖就可以了,我们提取一个接口后,代码就变成这样:

复制代码 代码如下:

class You {
    public void work() {
        int youMoney = 10;
        Peldar peldar= new Butcher();                               // find a peldar.
        int meat = peldar.buyMeat(youMoney);
        System.out.println("Cook the meat, weight: " + meat);        // you cooked it.   
    }
}
interface Peldar {
 int buyMeat(int money);
}
class Butcher implements Peldar {
    @Override
    public int buyMeat(int money) {
        Farmer farmer = new Farmer();            // 1.find a farmer.
        int meat = farmer.buyMeat(money);        // 2.buy meat from the farmer.
        meat += 5;                               // 3.inject 5 pound water into the meat, so weight will increase.
        return meat;                             // 4.return to you.
    }
}

class Farmer implements Peldar {
    @Override
    public int buyMeat(int money) {
        int meat = 0;
        // ... meat = ***;
        return meat;
    }
}

以上就是java动态代理详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java