- Notifications
You must be signed in to change notification settings - Fork 10
Calculator Example
Ben Fagin edited this page Aug 17, 2013
·
5 revisions
Let's build a calculator! Using the built-in BigInteger class we can easily construct a fluent api to access some of the math operations.
publicstaticclassResultextendsAtomicReference<BigInteger> { }
Descriptordescriptor = Flapi.builder()
.setDescriptorName("Calculator")
.setPackage("unquietcode.tools.flapi.examples.calculator.builder")
.setStartingMethodName("begin")
.startBlock("Calculation", "$(int startingValue)").last()
.addMethod("plus(int value)").any()
.addMethod("minus(int value)").any()
.addMethod("times(int value)").any()
.addMethod("divide(int value)").any()
.addMethod("power(int value)").any()
.addMethod("mod(int value)").any()
.addMethod("abs()").any()
.addMethod("equals()").last(Result.class)
.endBlock()
.build();The usage is fairly straightforward, and looks something like this:
Result_result = CalculatorGenerator.begin(newCalculatorHelperImpl())
.$(0)
.plus(1)
.plus(1)
.power(5)
.divide(2)
.equals();
BigIntegerresult = _result.get();
System.out.println(result);If you were to include this builder in a project, you might want to wrap some of the messiness involved with instantiating a new builder. A user of the calculator should not have to instantiate the helper or remember the $(...) method to begin. Here I've introduced a Calculator class which wraps all this up.
staticclassCalculator {
staticCalculationBuilder<AtomicReference<BigInteger>> begin(intstartingValue) {
CalculatorBuilder.$result = CalculatorGenerator.begin(newCalculatorHelperImpl());
CalculationBuilderbuilder = result.$(startingValue);
returnbuilder;
}
}And now the usage is just a tiny bit cleaner:
Result = result = Calculator.begin(0)
.plus(1)
.plus(1)
.power(5)
.divide(2)
.equals();
System.out.println(result.get());The full example can be found here.