-
Notifications
You must be signed in to change notification settings - Fork 11
House Builder Example
Using the last(Class)
method in a descriptor, it is possible to return a value from
a method or when leaving a block. In the HouseBuilder example, two different objects
are returned from the same builder.
As well, this descriptor showcases 'implicit terminals', which are generated when
there are no last()
methods within a block and all of the other methods have been
called their maximum number of times. In the HouseBuilder this is seen in the addWall()
block. After both the color and width have been set, the block returns.
On its own, the generated builder will not enforce a maximum outside of automagically making methods disappear. If you need to limit the number of objects returned, simply store a flag in your helper and refuse to return another object if called.
The descriptor:
Descriptor descriptor = Flapi.builder()
.setDescriptorName("House")
.setPackage("unquietcode.tools.flapi.examples.house.builder")
.startBlock("Wall", "addWall()").last(Wall.class)
.addMethod("setColor(java.awt.Color color)").atMost(1)
.addMethod("setWidth(double inches)").atMost(1)
.endBlock()
.addMethod("constructExpensiveHouse()").last(ExpensiveHouse.class)
.addMethod("constructAffordableHouse()").last(AffordableHouse.class)
.build();
And the corresponding usage:
HouseBuilder<Void> houseBuilder = HouseGenerator.create(new HouseHelperImpl());
// using the builder
Wall wall1 = houseBuilder.addWall()
.setWidth(120.35)
.setColor(Color.RED) // implicit terminal
;
Wall wall2 = houseBuilder.addWall()
.setColor(Color.BLACK)
.setWidth(87.45) // implicit terminal
;
// using both the builder and the object
Wall wall3 = houseBuilder.addWall()
.setColor(Color.BLACK)
.setWidth(80.25)
;
wall3.isWeightBearing(true); // this method isn't on the builder
AffordableHouse option1 = houseBuilder.constructAffordableHouse();
ExpensiveHouse option2 = houseBuilder.constructExpensiveHouse();
The full source can be found here.