Creator - examples

Printer-friendly versionPrinter-friendly version
How to use the Creator framework

 

Let's say we have a client class where we want to create an object of the type Foobar. And Foobar is an abstract class with 2 concrete extensions: ConcreteFoobar1 and ConcreteFoobar2. Note: for the purposes of this example, Foobar might represent whatever type of object we want: an entity, business object or data transfer object as well as a "stateless" service, data access object, etc.

public abstract class Foobar {
    
    private Foo foo;
    
    public Foobar(Foo foo) {
        this.foo = foo;
    }
    
    public Foo getFoo() {
        return this.foo;
    }
    
    public void doFoobarStuff() {
        // generalized foobar behavior
    }
    
}

The 2 concrete extensions just override the method doFoobarStuff() in order to alter the bahavior.

First of all we need to implement an abstract factory - so we can use that factory type already to implement the creator, which will depend on it.

public abstract class Domain1Factory extends GenericFactory {
    
    abstract public Foobar create(FoobarCreator creator);
    
}

Note: this will not compile yet, because the FoobarCreator is not yet existing (we implement the FoobarCreator next). If that worries you, just create an empty stub of the FoobarCreator first or add the factory method just after the FoobarCreator is implemented.   wink

The factories implement overloaded "create" methods. The extended factory (here GenericFactory) implements a default behavior for the case an implementation is missing in a concrete factory (here automatic object creation, even with arguments).

Note: Our system might consist of segregated subdomains or modules etc. and therefore employ different abstract factory types to support the segregation. That's why we implement that abstract extra level ("Domain1"). That is not necessary, but recommended for larger systems.

 

Pages