Modernized Pattern implementation with CDI, Part 1: The maximal decoupled “Parameterized Factory-Method-Pattern”


In this first part of my upcoming series I’d like to show you a new way of implementing the “factory-method” pattern. To be more precise, it is what the famous “Gang-of-Four” call a “parameterized factory-method” in the Design Patterns-Book (see the “Implementation” section of the “Factory Method Pattern” on page 110/111). For simplicity I will use the term “factory-method” synonym to “parameterized factory-method”. The crucial point here will be, that the factory no longer needs any compile-time dependencies upon any concrete interface implementation. Furthermore I will explain how to write un-mocked unit-tests for a CDI-Bean (the factory) in order to be able to check that all the CDI annotations work as desired without having to start an application server.

Why decoupling is desirable

If you ask why such decoupling is desirable, then you most likely have not yet worked on a project, where almost all modules depended on each other. This is a nightmare in many different aspects, but be assured, that such a system will be very hard to change and maintain. Thus always stick to Uncle Bob’s principle that any class or component should not depend on things that it doesn’t really need.


In order to understand this article, you should have a basic understanding of the Java(TM) language and you also know what dependency injection is. I also recommend that you look for some basic CDI examples if you haven’t got any experience with CDI yet.

The factory-method-pattern basics by introducing the example

In the example that I will use throughout this article, I assume we have to create a system that receives Match-Results for various kinds of sport.

The basic structure of the factory-method pattern

The basic structure of the factory-method pattern

In the above picture, you see the basis for a standard “parameterized factory-method”-pattern:

  • There is an interface, in our example it’s called “MatchResultValidator” with one or more generalized methods, here we have “validateMatchResult()”
  • There are sport-specific implementations of the interface, one for each type of sport: Football, Tennis, Darts etc…
  • There is the factory itself (“MatchResultValidatorFactory”). The factory-method receives one parameter, which is the object upon which the factory-method decides, which implementation the client actually needs. In our example the factory will make its decision upon the value object called “MatchResult”.

The XSD for the example

In my example, I assume that we have an XML-based interface to our system. Clients send XML-document instances of the root element called “MatchResult”. While MatchResult has some general attributes which are common to all kinds of sports, it also contains an xs:choice which binds a concrete instance of MatchResult to a certain sport. Here is the snippet from the XSD:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:complexType name="matchResultType">
            <xs:element name="homeTeamId" type="xs:long"/>
            <xs:element name="awayTeamId" type="xs:long"/>
                <xs:element name="footballResult" type="mr:timePeriodBasedGameResultType" />
                <xs:element name="handballResult" type="mr:timePeriodBasedGameResultType" />
                <xs:element name="icehockeyResult" type="mr:timePeriodBasedGameResultType" />
                <xs:element name="basketballResult" type="mr:timePeriodBasedGameResultType" />
                <xs:element name="tennisMatchResult" type="mr:individualMatchesBasedGameResultType" />
                <xs:element name="tableTennisMatchResult" type="mr:individualMatchesBasedGameResultType" />
                <xs:element name="billardMatchResult" type="mr:individualMatchesBasedGameResultType" />
                <xs:element name="dartsMatchResult" type="mr:individualMatchesBasedGameResultType" />
        <xs:attribute name="leagueId" type="xs:long" use="required"/>
        <xs:attribute name="matchId" type="xs:long" use="required"/>

As you can see, one instance of MatchResult can only be for one kind of sport. But many different sports share a similar kind of counting and result structure. Thus I have designed two different Result-structures that fit for many kinds of sports:

  • The “timePeriodBasedGameResultType” for sports like football where you have to halves or icehockey with three periods or basketball with four quarters and the outcome of each period is a score for each team. Of course the sum of all period scores makes up the total score for each team.
  • The “individualMatchesBasedGameResultType” is for team-sports like tennis, tabletennis or darts where each team-member plays one or more single matches against one player from the other team and also plays at least one double match. Each win in a single- or doublematch counts one point in the overall result.

Of course you could find some more Subtypes for MatchResult, but for this example, 2 different kinds are enough. Following you see an example for a Football-MatchResult:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<matchResult leagueId="4911" matchId="5012" xmlns="">
        <periodResult periodNumber="1">
        <periodResult periodNumber="2">

As you can see, the Subtype does not define how many periods it expects, because we want to reuse it for Football, Icehockey, Basketball. Thus we need a sports-specific validation of a MatchResult on the server-side. And this is finally where our factory will come into play.

The deployment-structure of the example

Before Dependency Injection (and especially CDI in our example), the factory was what “Uncle Bob” calls a “dependency magnet”, as it depended at compile-time on all concrete interface implementations (and transitively on their dependencies). With the following new, CDI-based solution, you can swap out the concrete interface implementations into separate “implementation”-modules, which the factory only needs to have available at runtime, but not at compile-time. This opens the doors for “independent develop-ability” of each concrete interface implementation which in turn makes it easier to split development tasks for specialized development teams or even external partners.

In my example, I assume that we have a WAR-file deployment called “matchresult-web” so that clients can send MatchResults via a REST-Interface. The REST-Service is located in the “matchresult-web” module and directly uses the factory. This is in order to keep the example as simple as possible. In real life applications, you will probably have additional layers in between like a facade- and a business-logic-layer. Finally, all the components will end up in the WEB-INF/lib of the WAR module.

My following explanations will focus on the blue components, because all the REST-Service-related stuff has nothing to do with the factory-method-pattern itself. Nevertheless, in order to make the example complete and allow for some integration-testing, I have added the WAR-module to the example code. But don’t worry, I will also show you how to unit-test such a CDI-based solution.

In the following diagram, I zoomed into the blue components in order to show you, which classes from the factory-method pattern go into which JAR module:


The glue: Defining CDI-Qualifiers for each concrete implementation

The key to the desired decoupling of the factory from the concrete interface implementations are “CDI-Qualifier-Annotations”. Each concrete implementation class must be annotated with its own special Qualifier. In our example, we define a Qualifier for each different kind of sport:

  • @Football
  • @Tennis
  • @Darts
  • etc…

In the following snippet, you can see how the @Football-Qualifier-Annotation is applied to the FootballMatchResultValidatorImpl-class:

public class FootballMatchResultValidator implements MatchResultValidator {

The @Football-Qualifier-Annotation itself is a normal Java-Annotation with the addition of the CDI- @Qualifier-Annotation:

public @interface Football {

The factory only knows the interface

In contrast to old-school-factory implementations, it is now possible, to define an instance variable for each concrete implementation by typing them all to the interface. Thus all instance variables are of type “MatchResultValidator”. This is the key to make the factory independent of the interface implementation classes.

public class MatchResultValidatorFactory {

    private MatchResultValidator footballMatchResultValidator;

    private MatchResultValidator tennisMatchResultValidator;

Qualification of the Injection Points inside the factory

As you can see in the above snippet, the glue between the concrete implementations and the instance variables of the factory are the CDI-Qualifier-Annotations. By annotating the instance variable “footballMatchResultValidator” with @Football, we tell the CDI-Container to inject the implementation of the interface which is itself annotated with @Football. If there is none, then the CDI-Container will fail on startup.

The factory-method: How to avoid large if-else cascades

Simple case: 1:1-relation between ValueObject-Type and interface implementation

If we had a different Java class for each kind of sport, then the factory can simply use a private Map where the key is the “Class<?>” of the value object and the map-value is the corresponding injected instance variable.

private final Map<Class<?>, MatchResultValidator> resultClassToValidatorMap = new HashMap<>();

This is not the case in our example, because we have the same root element type for all kinds of sport and it’s the choice inside the “MatchResultType” that makes the difference between the various kinds of sports. Anyway, in case of a 1:1-relation, the implementation of the factory-method itself would be a simple lookup into the map.

Please note that the population of the Map must happen inside a @PostConstruct-Lifecycle method of the Factory-Bean. The reason is, that if you would do it in a constructor like in old-school-implementations, then the CDI-Container does not yet have initialized the instance variables at that time and so you will effectively put null values into the map. I will demonstrate this also in the complex case below.

Complex case: Value-Object must be queried to find the correct implementation

In our case, the factory must look into the given value object in order to determine the correct instance variable. The resulting code would look something like this:

        if (matchResult.getFootballResult() != null) {
            return this.footballMatchResultValidator;
        if (matchResult.getTennisMatchResult() != null) {
            return this.tennisMatchResultValidator;
        if (matchResult.getXXX() != null) {
            return this.xxxMatchResultValidator;
        // and so on...
        throw new IllegalArgumentException("unknown MatchResult-Typ!");

This is considered bad programming style, you should generally try to avoid large if-else cascades.

One nice way to do it differently is via Java8 Functional Interfaces and Lambda Expressions Each if-condition goes into a separate lambda expression based on “java.util.function.Predicate”.

    private final Predicate isFootballMatchResult = tmr -> tmr.getFootballResult() != null;
    private final Predicate isTennisMatchResult = tmr -> tmr.getTennisMatchResult() != null;

Next, you still need a map to correlate each Predicate to its instance variable and you populate the map in the @PostConstruct Lifecycle method:

 private final Map<Predicate, MatchResultValidator> predicateToValidatorMap = new HashMap<>();

    public void postConstruct() {
        predicateToValidatorMap.put(isFootballMatchResult, footballMatchResultValidator);
        predicateToValidatorMap.put(isTennisMatchResult, tennisMatchResultValidator);

The factory-method implementation now needs to iterate through the map entries, test each Predicate and as soon as one predicate returns true, then it returns the corresponding map value. If no Predicate returns true, an IllegalArgumentException is thrown.

    public MatchResultValidator getMatchResultValidator(MatchResult matchResult) {
        Predicate fittingPredicate = predicateToValidatorMap.keySet().stream().
              filter(p -> p.test(matchResult)).findFirst().
              orElseThrow(() -> new IllegalArgumentException("unknown MatchResult-Type!"));
        return this.predicateToValidatorMap.get(fittingPredicate);

If you are not yet used to the Java8-Syntax with the Stream-API, then you can alternatively also write an old-school “imperative” for-loop.

Unit-Testing the Factory

In order to be able to write unit tests for the factory-method, such that you can make sure that the qualifier-based dependency injection has been setup correctly, two additional solution blocks come into play (compared to plain unit tests):

  • Separate Test-Module to avoid cyclic dependencies between modules
  • Apache Deltaspike framework for a convenient creation of a CDI-Environment in a standard Java VM.

Avoiding cyclic dependencies between modules

Usually a unit test is located in the same module as the production code that it wants to test. But for testing the correctly working dependency-injection, we need all the interface implementations in the classpath of the unit test.

In the productive WAR deployment, that’s no problem, because all the implementation modules are declared to be runtime-dependencies of the web application.

This means that the unit test – and so the module in which it is contained – must depend on all interface implementation modules. This would mean a dependency cycle because all these implementation modules already need to depend upon the factory-module, because this is where the interface is defined.

There are two solutions to this problem:

a) pull the interface out of the factory module and put it into a separate / new module.

b) create a separate test module for the factory-tests which can depend on all modules without any problem

I went for solution b) because I didn’t see a big benefit in separating the interface and the factory. The client will always need both of them. Actually, the creation of an additional production module would have been driven solely by the way of testing. This seems a bit strange to me and so I think it fits better to create a separate test module (“matchresult-factory-api-test”).


Once you have added the Deltaspike-dependencies to the pom of the test-module, the unit test can be implemented in a very straight forward way:


  • In line 20, the CdiTestRunner from Deltaspike is used to execute this unit-test. It creates the CDI container in which the unit test will run.
  • In lines 23/24 the “Object under Test”, the Factory itself gets injected into the unit test.
  • That’s it! Now the Factory is fully initialized and can be tested as desired!
    • In line 32, I use a static method of a utility class to create an instance of the value object “MatchResult”.
    • In line 33, I call the factory-method with this value object.
    • And finally in lines 35, I assert that the returned implementation class is of the type I expected it to be.

2 thoughts on “Modernized Pattern implementation with CDI, Part 1: The maximal decoupled “Parameterized Factory-Method-Pattern”

  1. Jeanette

    I really like what you guys are up too. This sort of clever work and exposure!
    Keep up the superb works guys I’ve incorporated you guys to my personal blogroll.

  2. Pingback: Modernized Pattern implementation with CDI, Part 2: The maximal decoupled “Chain Of Responsibility” | IT Blogs by Stephan Bauer

Leave a Reply

Your email address will not be published. Required fields are marked *