Last active
August 29, 2015 14:00
-
-
Save dmahapatro/5e35e59cad2736a6723f to your computer and use it in GitHub Desktop.
@builder AST Strategies sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Sample use cases of @Builder AST which is added in Groovy 2.3 */ | |
import groovy.transform.builder.* | |
import groovy.transform.ToString | |
//DefaultStrategy | |
@ToString(includeNames=true) | |
@Builder(builderStrategy=DefaultStrategy) | |
class Person { | |
String name | |
int age | |
} | |
//Uses field names as builder methods | |
println Person.builder().name( 'Jack' ).age( 10 ).build() | |
//DefaultStrategy with prefix | |
@ToString(includeNames=true) | |
@Builder(builderStrategy=DefaultStrategy, prefix='make') | |
class Hotel { | |
String name | |
int noOfRooms | |
} | |
//Uses prefixed method names | |
println Hotel.builder().makeName( 'MGM' ).makeNoOfRooms( 100 ).build() | |
//SimpleStrategy with prefix | |
@ToString(includeNames=true) | |
@Builder(builderStrategy=SimpleStrategy, prefix='with') | |
class Aircraft { | |
String type | |
int rank | |
} | |
//Uses prefix but initialization is self contained | |
println new Aircraft().withType( 'Citation X' ).withRank( 7 ) | |
//InitializerStrategy | |
@ToString(includeNames=true) | |
@Builder(builderStrategy=InitializerStrategy) | |
class Airport { | |
String name | |
String code | |
} | |
//Uses an initializer as a construct | |
println new Airport( Airport.createInitializer() | |
.name( 'John F Kennedy International Airport' ) | |
.code( 'JFK' ) ) | |
//ExternalStrategy | |
//Uses a separate Builder class externally | |
@ToString(includeNames=true) | |
class Car { | |
String make | |
String category | |
String type | |
} | |
//Explicit Builder Class for Car | |
@Builder(builderStrategy=ExternalStrategy, forClass=Car) | |
class CarBuilder { } | |
//User builder class | |
println new CarBuilder().make( 'Audi' ).category( 'Luxury' ).type( 'Sedan' ).build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment