代理模式

来源:互联网 发布:aq 网络中什么意思 编辑:程序博客网 时间:2024/06/05 12:49

为什么要有代理模式?

个人感觉是这样的:就类似于我们的社会,大的工厂是不会直接向用户卖产品的,而用户也不会直接去工厂去买货物,中间多了一层代理商,

代理商去工厂进货,然后卖给用户。这样工厂可以只关心生产商品的事情,并且只和代理商打交道。

如果还是很费解,不妨这样理解,比如你有一个很大的项目,已经稳定运行了,现在有个新的需求要你给***个用户提供一个服务,你愿意在

原来的类里面加这些逻辑吗?

最安全的方法应该就是在添加一个类,让这个类去管理***用户的各个需求,即使出了问题,不也不会影响原来的项目不是?这样子最安全。

 

这里给出一个简单的例子:

package model;

class Factory {
    public static int cargoCount = 0;

    public void produceCargo() {
        cargoCount++;
        System.out.println("factory build cargo," + cargoCount);
    }

    public int sellCargo() {
        return cargoCount--;
    }
}

public class Costumer {
    Proxy proxy;

    public Costumer(Proxy proxy) {
        this.proxy = proxy;
    }

    public void custom() {
        int cargo = proxy.getCargo();
        System.out.println("I get cargo:"+cargo);
    }

    public static void main(String[] args) {
        Proxy proxy = new Proxy();
        Factory facotry = new Factory();
        proxy.factory = facotry;
        Costumer costumer = new Costumer(proxy);
        costumer.custom();
    }
}

class Proxy {

    public static Factory factory;

    public int getCargo() {
        return factory.sellCargo();
    }
}

 

这样,即使customer怎么变,想退货,想买10个,一堆买家并发,只要proxy做操作就好了,工厂不用做任何的操作,

这样不就即便利,有高效吗?

原创粉丝点击