简体   繁体   中英

Supporting a public interface-based API and an internal concrete one concurrently?

I have designed a full API using interfaces, which clients can implement to make use of some behaviors. Internally I would like to make use of a richer API using my own implementation classes. I would like those implementations to continue conforming to the interface-based API, but Java's handling of generics is getting in the way.

Here is an example:

public interface PublicAPI {
    void doSomething(SomeType object);
}

public class SomeTypeImpl implements SomeType { }

public class InternalClass implements PublicAPI {
    public void doSomething(SomeTypeImpl object) {
        // ...
    }
}

In some cases it is possible to specify in the public api a type using wildcards, such as <T extends SomeType> , but this breaks down with generic collections which cause method clashing.

So I ask you, Is there any way of supporting this type of design (or a better design), or am I doomed to convert back and forth between my internal classes and an implementation of the public API?

Thanks!


UPDATE

I've gotten a better feel for why it isn't really possible to enforce a more specific type than what the API provides. Once anyone has an instance of your object it can be 'polluted' with less specific types.

Per the ACL suggestion, I've taken the approach of using internal classes within my own specific packages and then creating 'views' of them using the public API interfaces. Once a view is created, the object is flagged as impure and can no longer guarantee objects are of any type other than the interfaces. Within my own classes, I throw exceptions when an impure object is worked on (as this means a reference was allowed to leak prematurely).

I'll leave the question open to further insights.

Why don't you generify your interface? Something like:

public interface PublicAPI<T extends SomeType> {
    void doSomething(T object);
}

By the way you can extend your interfaces as:

public interface InternalPublicAPI extends PublicAPI { .... add your internal methods here }

There is such thing in Hibernate, there are Session and SessionImplementor interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM