1

How are Creational patterns useful? Most of the material I came across explains the use case to "solve common problems associated with object creation, improve flexibility".

I can think of just two similar cases where these might help:

  1. Encapsulating object creation code into a factory like class, so that all object creation code is in one place, and any modifications would require changes only in one place.

  2. Making object creation dynamic, whereby the required concrete type can be returned based on some parameters.

I am not able to exactly understand what problems creational patterns solve. What unfavourable consequences could one face by not using creational patterns?

It would be great if some one could elaborate on this with real code examples.

3
8

Why use creational patterns (in Java)?

The main reason for creational patterns is to separate the creation of an instance from its consumption.

That seems in the first place rather abstract, but has easy to see consequences.

1) You hide creational logic from the consument of an object-instance. As a consument you are not interested in how an instance is created. You only have a concrete demand (Service, Repository, etc.). Each demand is a dependency of your object. Which leads to

2) You are able to insert dependencies from the outside, aka dependency injection. If you are able to inject/substitute dependencies of an object, you are better able to write unit-tests. Say you need the result of a complex DB-query or the result of several web-service-calls; you could easily inject those results from the outside or stub results. Furthermore you could mock / stub out the creational objects itself, which could be used to deliver other mocks / stubs.

Better / more testable code leads to higher code coverage, which leads in the best case to better / higher code quality.

You could do your dependency injection by hand or use some kind of automation, e.g. Spring-framework or the like.

What unfavourable consequences could one face by not using creational patterns?

The downside of not using creational patterns should be clear from what was said above: It makes your code harder to understand and test.

real code examples:

Suppose you have a car, which itself has an engine. A typical way to implment it is this

public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(){
        engine=new Engine();
    }
}

public class Engine {

    public void start(){

    }

    public void stop(){

    }

}

You have a car, which instantiates its engine. Via the interface of the car, you are able to start/stop the car/engine.

This is bad in many ways:

1) you are not able to change the engine, the car runs with. That might not seem bad, since you intended the car to run only with the given engine

2) but, you could not swap the real engine_ out for a testengine.

You have to take two steps to improve the design:

1) separate the consumption of the engine from its use 2) use a factory pattern to encapsulate the creation of the engine

The improved car:

public class Car {

    Engine engine;

    public void start(){
        engine.start();
    }

    public void stop(){
        engine.stop();
    }

    public Car(Engine engine){
        this.engine=engine;
    }
}

The advantages are:

  • ability to swap the engine for the car
  • ability to swap the factory for the engine

So the whole creation of the car could be abstracted away with a builder:

public class CarBuilder {

    EngineFactory engineFactory;

    public Car build(){
        return new Car(engineFactory.produceEngine());
    }

    public CarBuilder(EngineFactory engineFactory){
        this.engineFactory=engineFactory;
    }

}

Which itself could be mocked/stubbed.

0
2

The Singleton is classified as a creational pattern, so that's one obvious use: ensuring that everybody always communicates with the same instance. (The benefits of this are controversial, but I didn't say it was a good use. Just a rather obvious use.)

Factory methods spare an API user from knowing (and maintaining over time) overly specific helper class names. When you order pizza, you don't care whether a MotorizedBicyclePizzaCourier, a WalkingPizzaCourier or a TeleportPizzaCourier serves you - you only need to know that you're dealing with a PizzaCourier. This leaves the pizza place free to introduce new delivery methods without requiring their customers to upgrade anything.

Builders allow you to simplify the low-level syntactical details of creating objects. That's not as world-shakingly important as some other things (which affect correctness or maintainability), but it's not nothing, and often a good idea for objects with many attributes.

That's not all, but I hope you get the idea: different creation patterns have different (although similar) uses and advantages. They are lumped into one category mainly because there are now too many design patterns to treat them all as one huge list.

1
  • Nicely put! This became more clear once I wrote some examples.
    – bub
    Nov 25 '14 at 10:55
1

One common benefit of a creational pattern is to change program behavior from one run to another. This could be done by a command-line argument, for example. Perhaps specifying a switch to enable functionality results in a factory creating a different type of object, say by creating a different type of output writer for a file vs. standard output. Maybe there are two types of controllers sharing a common interface. One is interactive, one must be fed in its inputs and runs without user interaction.

I do have a concrete example of a creational pattern: Log4j. The following XML snippet is copied from the sample XML configuration in the Log4j manual.

The code that reads this configuration will create an appender, layout, and filters based on the values specified in this section. It will link them together into a complete, usable object graph.

<Appender type="Console" name="STDOUT">
  <Layout type="PatternLayout" pattern="%m MDC%X%n"/>
  <Filters>
    <Filter type="MarkerFilter" marker="FLOW" onMatch="DENY" onMismatch="NEUTRAL"/>
    <Filter type="MarkerFilter" marker="EXCEPTION" onMatch="DENY" onMismatch="ACCEPT"/>
  </Filters>
</Appender>

While most applications will not delegate much of the object creation specification to external configurations, this is used quite heavily in certain applications. At one of my previous jobs there were quite a few factories and singletons used to customize behavior in the application and the implementations were specified in property files. When requesting an instance the code will check the class name to load (which must be the enclosing class or a subclass), allowing customer extensions.

This particular code is a brief example of how to construct a factory based on a system property. It would be possible to set a system property to use a subclass which might then override the createWidget() method to create different widgets.

public class MyFactory {

  public static MyFactory createFactory() {
    String implName = System.getProperty(MyFactory.class.getName());
    if (implName == null) {
      return new MyFactory();
    }
    else {
      try {
        Class<?> impl = Class.forName(implName);
        return impl.newInstance();
      }
      catch (Exception e) {
        throw (e instanceof RuntimeException
            ? (RuntimeException) e : new RuntimeException(e));
      }
    }
  }

  public Widget createWidget() { ... }
}
1

In Java, if DerivedFoo: BaseFoo, saying foo = new DerivedFoo(boz); will construct a new "blank" DerivedFoo instance and call the a DerivedFoo constructor that can take boz as a parameter. That constructor must in turn call one of BaseFoo's constructors before it is allowed to do much of anything with the object under construction or with the passed-in parameter. Once BaseFoo's constructor returns, BaseFoo will have no further control over the object under construction.

Note that there are many cases where code might know that it needs something that derives from DerivedFoo, but might not need a newly-created object of that exact type. Among other things:

  • In some cases, often identifiable based upon passed-in parameters, some other derivative of DerivedFoo might be better.

  • In some cases, especially with immutable types, the client may be better served by a pre-existing object than by a new one.

  • Some kinds of objects need to notify outside objects when they are created and ready for use, but the calling sequence for constructors doesn't notify the base-class object when the most derived constructor has finished executing, and doesn't even provide a terribly convenient way for a constructor to know if other more-derived constructors have yet to execute.

Factory methods can easily overcome all of these problems, since they can return new or pre-existing objects, and can invoke base-class initialize() method after the most derived constructor is finished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.