【问题标题】:How to implement proxy pattern involving async call?如何实现涉及异步调用的代理模式?
【发布时间】:2011-08-08 01:59:52
【问题描述】:

如何实现涉及异步调用的代理模式?

举个例子,如果我想得到一些东西,我会首先检查对象是否驻留在内存中,如果不是,我会发出http请求来检索它(这是异步调用)。

Customer customer;
customer = CustomerDAO.getCustomerByName("John");

在 CustomerDAO.getCustomerByName("John"); 内部;

Customer getCustomerByName(String name)
{
    int age = 40;

    if (map.contains(name)) 
    {
        Customer customer = map.get(name);
        customer.age = age;
        return customer;
    }
    else
    {
        makeRequestAsnyc(name, callback);
    }
}

但是由于它是异步的,它会破坏程序的流程。 getCustomers 中的任何局部变量也必须传递给回调函数。有什么建议用异步实现代理模式吗?谢谢。

【问题讨论】:

    标签: java design-patterns asynchronous proxy-pattern


    【解决方案1】:

    这个呢? (抱歉,我猜是“回调”类)

    Customer getCustomerByName(String name, Callback callback)
    {
        int age = 40;
    
        if (map.contains(name)) 
        {
            Customer customer = map.get(name);
            customer.age = age;
            callback.call(customer);
        }
        else
        {
            makeRequestAsnyc(name, callback);
        }
    }
    

    一般来说,当您已经拥有异步 API 时,您不希望引入阻塞方法。

    【讨论】:

    • 会断流customer = CustomerDAO.getCustomerByName("John");
    • @janetsmith:相反,我建议您在此处键入的代码行会破坏 API 的异步特性,如果您可以避免它,这不是一个好主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多