Java Reference
In-Depth Information
LISTING 6‐31: (continued)
m = mf.getMessage(Message.Type.LONG);
m.setMessage("This is a long message");
This chapter has deviated quite substantially from the original GoF implementation of the factory
pattern. In fact, you could argue that this is not really a true factory pattern implementation but
rather a select and inject pattern. Nevertheless, the new and dynamic functionality of CDI allows
you to be creative in the way you implement traditional patterns and improve on classic design.
The traditional implementation of the factory pattern has changed substantially since the GoF i rst
espoused its usage.
Abstract factories are considered an effective way to hide object creation, especially if the creation
is complex. And the more complex the object creation, the more justii able is the use of a factory to
create the object. If it is important that objects are created in a consistent manner and their creation
is strictly controlled, you should consider an implementation of the factory pattern.
However, in the brave new world of the CDI environment, where the container instantiates managed
objects, the use of an abstract factory is arguably moot. Your best attempt to implement the factory
pattern uses the @Produce annotation that still allows you to hide complicated creational logic in
the producer method and inject the resulting object into the client.
Alternatively, you can harness the power of the CDI environment and let the container create the
objects and then select the instantiation you want to use from a pool of similar objects. However,
you are limited to simple objects that can be instantiated satisfactorily by calling the default
In this chapter, you have seen how to implement the various l avors of the factory pattern in a
non‐CDI environment. And in a CDI environment, you have seen how producer methods and the
@Inject annotation have radically changed the way you implement and use the factory pattern in
Java EE.
You have discovered how to harness the power of the container's automatic instantiation of bean
objects and how to select and use them in your code.
Hopefully, you have no doubt that the implementation of the factory pattern in a Java EE is
substantially more elegant and by far the simpler and cleaner way to generate objects.
Search WWH ::

Custom Search