Java Reference
In-Depth Information
}
public Type value() {
return type;
}
}
Now that you have all the parts of the puzzle, you can put it together in the
MessageFactory
class
shown in Listing 6-30.
LISTING 6‐30:
The Factory implementation
@Dependent
public class MessageFactory {
@Inject
@Any
private Instance<MessageType> messages;
public MessageType getMessage(Message.Type type) {
MessageLiteral literal = new MessageLiteral(type);
Instance<MessageType> typeMessages = messages.select(literal);
return typeMessages.get();
}
}
In the factory class, all dependencies that implement the
MessageType
interface are injected into
the member variable
messages
. Then, from the method
getMessage
, you use the
Message.Type
parameter to create a new
MessageLiteral
that you use to select the
MessageType
implementation
that you want from
messages
, which in turn is returned to the client.
The client injects the factory and calls the
getMessage
method passing in the
Message.Type
that it
requires, as can be seen in Listing 6-31.
LISTING 6‐31:
Client using the Factory implementation
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@ApplicationScoped
public class Client {
@Inject
MessageFactory mf;
public void doMessage(){
MessageType m = mf.getMessage(Message.Type.SHORT);
m.setMessage("This is a short message");
continues