Builders/Factories and Inheritance.

D

Daniel Pitts

I was just thinking about the Builder pattern (because of Roedy's recent
post).

It seems to me that Builders are a special type of Factory, and in
general Factories /tend/ to prevent the client from specifying the
actual implementation to use. I was thinking about ways to give the
client some control, while allowing the builder to do its job as-well.

I was thinking of a double-indirection factory (bad name maybe?)

class Foo { public Foo(int bar, Baz baz) {} }

interface FooFactory {
Foo createFoo(int bar, Baz baz);
}

class FooBuilder {
private final FooFactory factory;
public FooBuilder(FooFactory factory) {this.factory = factory;}
public FooBuilder() {this.factory = new DefaultFooFactory();}
// builder methods etc...

public Foo toFoo() { return factory.createFoo(getBar(), getBaz()); }
}


This gives the client the ability to create a subclass foo builder, and
utilize the foo builder:
class SpecialFoo extends Foo {
SpecialFoo(int bar, Baz baz, Zip zip) {
super(bar, baz);
}
}

class SpecialFooBuilder implements FooFactory {
// builder methods to get "zip"
Foo createFoo(int bar, Baz baz) {
return new SpecialFoo(bar, baz, zip);
}
}


class Client {
public void stuff() {
SpecialFooBuilder specialFooBuilder = new SpecialFooBuilder();
FooBuilder fooBuilder = new FooBuilder(specialFooBuilder);
configureSpecialFooBuilder(specialFooBuilder);
configureFooBuilder(fooBuilder);
fooBuilder.toFoo().doFooThing();
}
}

This seems like it *might* be an anti-pattern, but I'm not sure. Have
any of you had to implement this design? How did it work out? I don't
actually have any real code for this, since I'm just thinking "out loud"
at the moment.
 
O

Owen Jacobson

I was just thinking about the Builder pattern (because of Roedy's recent
post).

It seems to me that Builders are a special type of Factory, and in
general Factories /tend/ to prevent the client from specifying the
actual implementation to use.  I was thinking about ways to give the
client some control, while allowing the builder to do its job as-well.

I was thinking of a double-indirection factory (bad name maybe?)

class Foo { public Foo(int bar, Baz baz) {} }

interface FooFactory {
   Foo createFoo(int bar, Baz baz);

}

class FooBuilder {
   private final FooFactory factory;
   public FooBuilder(FooFactory factory) {this.factory = factory;}
   public FooBuilder() {this.factory = new DefaultFooFactory();}
   // builder methods etc...

   public Foo toFoo() { return factory.createFoo(getBar(), getBaz()); }

}

This gives the client the ability to create a subclass foo builder, and
utilize the foo builder:
class SpecialFoo extends Foo {
    SpecialFoo(int bar, Baz baz, Zip zip) {
       super(bar, baz);
    }

}

class SpecialFooBuilder implements FooFactory {
    // builder methods to get "zip"
    Foo createFoo(int bar, Baz baz) {
     return new SpecialFoo(bar, baz, zip);
    }

}

class Client {
   public void stuff() {
       SpecialFooBuilder specialFooBuilder = new SpecialFooBuilder();
       FooBuilder fooBuilder = new FooBuilder(specialFooBuilder);
       configureSpecialFooBuilder(specialFooBuilder);
       configureFooBuilder(fooBuilder);
       fooBuilder.toFoo().doFooThing();
   }

}

This seems like it *might* be an anti-pattern, but I'm not sure.  Have
any of you had to implement this design? How did it work out?  I don't
actually have any real code for this, since I'm just thinking "out loud"
at the moment.

Without context it's hard to say if that structure is good or bad, but
it *is* awfully verbose. It'd read somewhat better in a language with
lambdas, I think, and as written it'd be easier to do most of the
connections using spring or something like it rather than having the
client directly responsible for creating the factories and builders.

I can see something like this (separating the actual creation logic
from configuration logic) for writing parsers, where the parser
interacts with a builder for building up the final object to
construct, but the builder delegates to a factory-as-strategy for the
final creation step.

-o
 
M

Mark Space

Daniel said:
class FooBuilder {
private final FooFactory factory;
public FooBuilder(FooFactory factory) {this.factory = factory;}
public FooBuilder() {this.factory = new DefaultFooFactory();}
// builder methods etc...

public Foo toFoo() { return factory.createFoo(getBar(), getBaz()); }
}

This bit here seems very similar to "The Service Provider Pattern." You
might want to check that out. The FooFactory you have seems to be
providing the the "service" of building Foos.

This would work a bit like JDBC, where the end-user specifies some
action to connect, and the framework is able to find the particular
connector ("client" in you example), install it as the factory builder,
and return a requested instance. All in one go...


This seems like it *might* be an anti-pattern, but I'm not sure. Have
any of you had to implement this design? How did it work out? I don't
actually have any real code for this, since I'm just thinking "out loud"
at the moment.


I don't think it's an anti-pattern, but it might be a sophisticated one
that isn't used all the time due to it's internal complexity. Like
JDBC. You'd have to know a lot about how the FooBuilder super class
worked to be certain you implemented all the needed requirements. If
the requirements are trivial, then I don' think the builder pattern is
as useful. The more complex the builder, the more useful it is.

I'd probably make FooBuilder into an interface (assuming the builder is
complex enough to be practical, it probably warrants an interface).
 
T

Tom Anderson

I was just thinking about the Builder pattern (because of Roedy's recent
post).

Stop - digression time! I get the impression that there are at least two
different patterns that go by the name 'Builder'.

I don't own a copy of the Gang of Four book, so i can't check what they
wrote, but i think they describe something that's a bit like the
relationship between an XML parser and a DocumentFactory, where you have a
Director that knows what steps have to be performed, and a Builder that
knows how to execute the steps, and where the steps ultimately yield a
complex Product of some sort. To put it another way, the Builder provides
the primitives, and the Director uses the primitives. This allows
decoupling of organisation and the details of the representation - in the
XML case, the factory can build DOM nodes optimised for size, or for
speed, or with javascript support, or using some persistence technique to
transparently handle huge documents, or whatever.

The other pattern, which i *think* might originate in a talk by Josh
Bloch, is where a Builder is essentially a mutable, fairly passive holder
for state that is then used to construct some Product in a single big-bang
constructor invocation. The point of this is that you can make creation of
the Product easier without having to allow partially-constructed Products
to exist.

Here's an example of the first builder (sorry that this is so long-winded,
but it's a complicated pattern):

interface Document {
public List<Element> getElements() ;
}

interface Element {
public String getText( ;
}

interface Heading extends Element {
public int getLevel() ;
}

interface Paragraph extends Element {
}

interface DocumentBuilder {
public void addHeading(int level, String text) ;
public void addParagraph(String text) ;
public Document getDocument() ;
}

// details omitted due to tediousness
class HTMLDocument implements Document // ...
class HTMLElement implements Element // ...
class HTMLHeading implements Heading // ...
class HTMLParagraph implements Paragraph // ...

class PDFDocument implements Document // ...
// etc for PDF versions of other interfaces

class OlympicAwardDirector {
public Document make(DocumentBuilder builder, String athlete, String event, MedalLevel level)
builder.addHeading(1, "Certificate of Olympic Award") ;
builder.addHeading(2, "Preamble") ;
builder.addParagraph("Mumble mumble er Beijing 2008"
+ " spirit of sportsmanship etc") ;
builder.addHeading(2, "Details of Award") ;
builder.addParagraph("This is to certify that a " + level
+ " medal has been awarded to " + athlete
+ " in the " + event) ;
builder.addParagraph("God Save Chairman" Mao") ;
return builder.getDocument() ;
}
}

void someClientMethod() {
DocumentBuilder db = new PDFDocumentBuilder() ;
OlympicAwardDirector dir = new OlympicAwardDirector() ;
Document cert = dir.make(db, "Rebecca Adlington", "800m freestyle", MedalLevel.GOLD) ;
}

Here's an example of the second:

class Medal {
public Medal(MedalLevel level, Event event, String athlete, Nation nation ) // ...
}

class MedalBuilder {
private MedalLevel level
private Event event ;
private String athlete ;
private Nation nation ;

public void setLevel(MedalLevel level) {
this.level = level
}
public void setEvent(Event event) {
this.event = event ;
}
public void setAthlete(String athlete) {
this.athlete = athlete ;
// just to make things interesting:
this.nation = Nation.getForAthlete(athlete) ;
}
public Medal build() {
return new Medallevel, event, athlete, nation() ;
}
}

void someClientMethod() {
mb.setAthlete("Rebecca Adlington") ;
mb.setEvent("800m freestyle") ;
mb.setLevel(MedalLevel.GOLD) ;
Medal m = mb.build() ;
}

Digression over - this is not really an answer to your question. Your
design seems to include some of both. Perhaps this is not uncommon.
It seems to me that Builders are a special type of Factory, and in general
Factories /tend/ to prevent the client from specifying the actual
implementation to use. I was thinking about ways to give the client some
control, while allowing the builder to do its job as-well.

I was thinking of a double-indirection factory (bad name maybe?)

What you've got here is a combination of Builder and Decorator. Sort of.
This seems like it *might* be an anti-pattern, but I'm not sure. Have
any of you had to implement this design? How did it work out? I don't
actually have any real code for this, since I'm just thinking "out loud"
at the moment.

I've never written a class complicated enough to need this sophisticated a
construction pattern, but imagine if i did, it would be a good solution.

The major alternative is to subclass FooBuilder to make SpecialFooBuilder,
adding the extra fields and setters, and then overriding the build()
method. That would, i think, be simpler, but i think your approach is
cleaner. Also, it's compatible with the use of the first style of Builder
above, in that the kind of FooBuilder can be varied, while using the same
SpecialFooBuilder. Although in your case, the FooBuilder is really a
Director. I think.

tom
 
E

Ed Kirwan

Daniel said:
I was just thinking about the Builder pattern (because of Roedy's recent
post).

It seems to me that Builders are a special type of Factory, and in
general Factories /tend/ to prevent the client from specifying the
actual implementation to use. I was thinking about ways to give the
client some control, while allowing the builder to do its job as-well.

(Nose-diving towards OT): I appreciate the highlighted, "Tend," though I
find that 90% of my client interaction with factories is via the
parameterised factory method (in which, as you know, the client has rather
a sizable say in the returned object though without ever dirtying itself
with knowledge of the actual implementation) rather than naked factories
themselves.

Where I use factories proper, they tend to decide the returned object based
on environmentally-specified configuration options.

Just my two kroner.
 
D

Daniel Pitts

Tom said:
Stop - digression time! I get the impression that there are at least two
different patterns that go by the name 'Builder'.

I don't own a copy of the Gang of Four book, so i can't check what they
wrote, but i think they describe something that's a bit like the
relationship between an XML parser and a DocumentFactory, where you have
a Director that knows what steps have to be performed, and a Builder
that knows how to execute the steps, and where the steps ultimately
yield a complex Product of some sort. To put it another way, the Builder
provides the primitives, and the Director uses the primitives. This
allows decoupling of organisation and the details of the representation
- in the XML case, the factory can build DOM nodes optimised for size,
or for speed, or with javascript support, or using some persistence
technique to transparently handle huge documents, or whatever.

The other pattern, which i *think* might originate in a talk by Josh
Bloch, is where a Builder is essentially a mutable, fairly passive
holder for state that is then used to construct some Product in a single
big-bang constructor invocation. The point of this is that you can make
creation of the Product easier without having to allow
partially-constructed Products to exist.
I think they are possibly similar enough in concept that they can be
called the same thing. The big difference between a configurable
factory, and a Builder in the sense that you presented is that the order
of method invocation doesn't typically matter on the "Factory" (save the
factory method), where it does on the builder. Take StringBuilder as a
very basic example. Its output depends on the order that methods are
called on the builder object, where as a Factory class usually shouldn't
care the order that a property is configured, as long as enough are
configured at factory time.
What you've got here is a combination of Builder and Decorator. Sort of.


I've never written a class complicated enough to need this sophisticated
a construction pattern, but imagine if i did, it would be a good solution.

The major alternative is to subclass FooBuilder to make
SpecialFooBuilder, adding the extra fields and setters, and then
overriding the build() method. That would, i think, be simpler, but i
think your approach is cleaner. Also, it's compatible with the use of
the first style of Builder above, in that the kind of FooBuilder can be
varied, while using the same SpecialFooBuilder. Although in your case,
the FooBuilder is really a Director. I think.
Interesting, I'll have to think about that some more. It could be that
SpecialFooBuilder is actually a Strategy, rather than a Factory; that
might would make FooBuilder a Director.
 
D

Daniel Pitts

Ed said:
(Nose-diving towards OT): I appreciate the highlighted, "Tend," though I
find that 90% of my client interaction with factories is via the
parameterised factory method (in which, as you know, the client has rather
a sizable say in the returned object though without ever dirtying itself
with knowledge of the actual implementation) rather than naked factories
themselves.

Where I use factories proper, they tend to decide the returned object based
on environmentally-specified configuration options.

Just my two kroner.
Granted, that is the most common use-case for builders/factories. It
does allow the client to "not care" about the actual implementation
type. This is good in most cases, but there are times when the client
might want to alter some behavior, and writing a delegate or wrapper
instead of overriding a method or two doesn't make sense or isn't
feasible. Of course, that problem can probably be solved in other ways
(Decorator pattern, for instance.)

Thanks for the feed back.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top