Monday, 28 November 2011

JavaEE Revisits Design Patterns: Factory Pattern

Factory pattern is a popular pattern among most of the programming languages. The idea behind factories are encapsulating the object creation which may subject to change.
Factory Pattern might be considered as one of the easy to understand and implement design pattern which also can be quite useful. However, the implementation even gets easier JavaEE6.

In JavaEE world '@Produces' annotation is used to create object factories and '@Inject' (aka dependency injection) is used for injecting the needed resource to where approciate. Here is a simple example based on the last post.

package com.devchronicles.producer;
import javax.enterprise.inject.Produces;

 * @author Murat Yener
public class EventProducer {
    public String getMessage(){
        return "A message!!";

The method annotated with '@Produces' produces string objects. Although the type produced is given as string, you may choose any Java type or your own objects and let the producer method to act as a factory for you.

To use the produced objects we need to inject the same type.


import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;

 * @author Murat Yener
public class EventService {
    private String message;
    public void startService(){
        System.out.println("start service call "+message);

When you run and invoke the startService method you will see the string value in the producer method to be injected and printed on the console. Although it might seem a bit magical, JavaEE Producer annotation relies on types which is String in our case, to create objects and inject them when they are asked for,

Producer annotation offers a simple and easy to implement and use. It simply constructs the object type given which works quite well and simple.
To construct and Inject your own types you may create new Classes or Annotate the injection so a String class might be produced by different factories.

1 comment:

  1. Question, how does the Event Service class know that the Factory class is what it will be using when the injection occurs