What if in bridge pattern, Abstraction has an AutoClosable implementer

For people who are familiar with bridge pattern, we know it uses composition to include the concrete implementer as part of the refined abstraction. so basically we are expected to use the Abstraction as a client of this pattern. /--Implementer--/ Interface Implementer extends AutoClosable { public void open(); public void close(); }

/**--Concrete ImplementerA--**/
ImplementerA implements Implementer {
    public void open(){....};
    public void close(){......};
public abstract class Abstraction {
    protected Implementer implementer;
    public methodAIwant2use();
    public methodBIwant2use();
/**--Refined Abstration--**/
public class RefinedAbstraction {
    public RefinedAbstraction(String Implementer) {
    public methodAIwant2use();
    public methodBIwant2use();

As the code above shown, I've hit an issue where my implementer happens to be an AutoClosable. In my case, I will directly use Abstraction at the client side and use a string as the constructor parameter to determine what concrete implementer I will use. But this kinda leaves me in a situation where I can't use try-with-resources(Abstraction ab = new RefinedAbstraction("implementorA")), because Complier would complain that my abstraction is not a AutoCloseable. It doesn't make sense to put concreteImplementor instance in the try-with-resouces block, because it's the methods in Abstraction Interface actually wanted here.

The only way to get around this I can think of is that, I can use try/catch with finally block to explicitly close out my Abstraction.implementer instead of trying to use try-with-resources. But doing this means I have to increase the visibility of the implementer from protected to public which is not nice.

Any thoughts? or better approach for this?


You could make Abstraction itself an AutoCloseable and leave close() empty. A subclass that composes autocloseables would then override close to delegate the call to the composed object. Your client can then treat all Abstractions as autocloseable and interact with them consistently by using try-with-resources.

Need Your Help

Sorting an ArrayList on a child's value in C#

c# arrays sorting

I have an ArrayList that contains multiple String[] (String arrays).

How can I enlist an ODBC connection in an XA 2PC transaction?

jdbc transactions odbc xa 2phase-commit

Our application uses ODBC to communicate with a database (Both DB2 and Oracle, if it makes a difference), and delegates business logic to Java by way of JNI (So it uses Java and C).