java中的委托实现

发布于 2024-10-28 22:14:42 字数 106 浏览 1 评论 0原文

据我了解,委托用于解耦客户端和业务层。客户端通过委托对象调用业务服务。我的问题是,将委托接口暴露给客户端(按契约原则设计或 DIP)而不是实际的委托对象是否好。或者让客户端直接访问委托对象就可以了。

I understand that a delegate is used to decouple client and business layer. A client invokes a business service through delegate object. My question is that is it good to have interface of delegate exposed to client (Design by contract principle OR DIP) not the actual delegate object. Or is it just fine to have a delegate object accessed by the client directly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

远昼 2024-11-04 22:14:42

我会选择界面,因为这可以让我将所做的事情与如何做分开。我可能会发现让委托成为代理或用一个方面来装饰它是有利的;两者都可以通过界面轻松实现。

I would opt for the interface, because that would allow me to separate what's done from the how. I might find it advantageous to made the delegate a proxy or decorate it with an aspect; both are easy with an interface.

谈下烟灰 2024-11-04 22:14:42

我相信您可能会混淆客户端使用的外部 API(外观)和实际通过委托调用的代码:

public class Worker implements IWorker {
    private IProcessor delegate;

    void doWork(PublicDO data) {
      PrivateDO pdo = convert(data);
      delegate.doProcess(pdo);
    }
...
}

委托不一定具有与外观相同的接口。此外,委托接口可以更改,而公共接口保持不变。可能有多个委托实现略有不同,在运行时根据某些参数进行实例化。

因此,将公共接口和委托接口分开总是一个好主意。

与公共外观具有相同接口的委托只是最简单的情况。

I believe you may be confusing the external API (facade) that client uses and the code that actually get invoked via delegate:

public class Worker implements IWorker {
    private IProcessor delegate;

    void doWork(PublicDO data) {
      PrivateDO pdo = convert(data);
      delegate.doProcess(pdo);
    }
...
}

Delegate not necessary has the same interface as facade. Moreover, delegate interface can be changed while the public interface is kept unchanged. There are may be multiple delegate implementation that differ slightly, instantiated at runtime based on some parameters.

Thus it is always a good idea to separate public interface and delegate interface.

Delegate having the same interface as public facade is just the simplest case.

∝单色的世界 2024-11-04 22:14:42

您可以查看维基百科:

http://en.wikipedia.org/wiki/Delegation_pattern

有片段爪哇

再见

You can see wikipedia:

http://en.wikipedia.org/wiki/Delegation_pattern

there's snippet in java

bye

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文