Creator - examples
Corresponding to the abstract Domain1Factory we implement an abstract Domain1Creator.
public abstract class Domain1Creator<T> extends Creator<T, Domain1Factory> {}
Now we can implement the Creator. Even if we opt for an automatic generation of the Creator classes, we should always know how to implement them by hand. Anyway it's a piece of cake!
public class FoobarCreator extends Domain1Creator<Foobar> {
private Foo foo;
public Foobar(Foo foo) {
this.foo = foo;
}
public Foo getFoo() {
return this.foo;
}
@Override
public Class<Foobar> getType() {
return Foobar.class;
}
@Override
public Foobar create(Domain1Factory factory) {
return factory.create(this);
}
}
As you can see we just copied the field, constructor and getter from Foobar. Then we extend the abstract Domain1Creator providing as generic parameter the type we create objects from.
We added to the creator one method that simply returns the type we create objects for and one method to perform the actual creation of objects. The latter performs a dispatch on the overloaded factory method.
Now it's time to implement the concrete factories. One factory for the behavior of ConcreteFoobar1 and one factory for the behavior of ConcreteFoobar2.
public class ConcreteFactory1 extends Domain1Factory {
@Override
public Foobar create(FoobarCreator creator) {
return new ConcreteFoobar1(creator.getFoo());
}
}
public class ConcreteFactory2 extends Domain1Factory {
@Override
public Foobar create(FoobarCreator creator) {
return new ConcreteFoobar2(creator.getFoo());
}
}
Seiten |