java – 如果在桥接模式中,Abstraction有一个AutoClosable实现者
对于熟悉桥模式的人,我们知道它使用组合来包含具体实现者作为精炼抽象的一部分.所以基本上我们应该使用抽象作为这种模式的客户.
????/ – 实施者 – / /**--Concrete ImplementerA--**/ ImplementerA implements Implementer { public void open(){....}; public void close(){......}; } /**--Abstration--**/ public abstract class Abstraction { protected Implementer implementer; public methodAIwant2use(); public methodBIwant2use(); } /**--Refined Abstration--**/ public class RefinedAbstraction { public RefinedAbstraction(String Implementer) { this.implementer=Implementer; } public methodAIwant2use(); public methodBIwant2use(); } 正如上面显示的代码,我遇到了一个问题,我的实现者恰好是AutoClosable.在我的例子中,我将直接在客户端使用Abstraction并使用字符串作为构造函数参数来确定我将使用的具体实现者.但是这种情况让我无法使用try-with-resources(Abstraction ab = new RefinedAbstraction(“implementorA”)),因为Complier会抱怨我的抽象不是AutoCloseable.将concreteImplementor实例放在try-with-resouces块中是没有意义的,因为这是Abstraction Interface中实际需要的方法. 解决这个问题的唯一方法我可以想到,我可以使用try / catch和finally块来明确地关闭我的Abstraction.implementer,而不是尝试使用try-with-resources.但这样做意味着我必须提高实施者从受保护者到公众的可见性,这是??不好的. 有什么想法吗?或更好的方法吗? 解决方法
您可以将Abstraction本身设置为AutoCloseable并将close()留空.然后,组成autocloseables的子类将覆盖close以委托对组合对象的调用.然后,您的客户端可以将所有抽象视为自动关闭,并使用try-with-resources始终与它们进行交互.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |