James Raitsev
James Raitsev

Reputation: 96391

Collection of Interfaces to pick from, Java

Consider that object wrapped in DataContainer will be handed out to client

// Will be handed out
public interface DataContainer 

In order to use it, client currently needs to know to cast the object to:

public interface ConcreteObject_1_Container extends DataContainer
public interface ConcreteObject_2_Container extends DataContainer

Is it possible to offer both ConcreteObject1Container and ConcreteObject2Container as options to be chosen from, similar to how Enum options can be picked?

Instead of user magically knowing to use FileContainer

                                   // user knows
FileContainer   fileContainer   = (FileContainer) 
                ContainerFactory.getContainerFor(DataSource.FILE, 
                                                 TREAT_AS_SOURCE);

I'd like to

                                  // user selects
FileContainer   fileContainer   = (GenericContainer.FileContainer) 
                ContainerFactory.getContainerFor(DataSource.FILE, 
                                                 TREAT_AS_SOURCE); 

Upvotes: 3

Views: 87

Answers (2)

artbristol
artbristol

Reputation: 32407

You should probably change your design. Either:

  1. the client just uses the methods on DataContainer, without caring what implementation it is, in which case the cast can be avoided, or
  2. the client is actually coupled to the implementation, so should just use the implementation types directly (e.g. with two different methods)

Upvotes: 6

Shamik
Shamik

Reputation: 7108

If you can make getConatainerFor a generic method, then it will be able to return the specific type using type inference.

Upvotes: 0

Related Questions