1. 程式人生 > >Groovy學習筆記-Java 5新特性支持

Groovy學習筆記-Java 5新特性支持

analyze port static ring leg break main uniq size

1.枚舉enum

enum CoffeeSize{
    SHORT,
    SMALL,
    MEDIUM,
    LARGE,
    MUG
}

def orderCoffee(size){
    print "Coffee order received for size $size:"
    switch(size){
        case [CoffeeSize.SHORT, CoffeeSize.SMALL]:
            println ‘Conscious‘
            break;
        
case CoffeeSize.MEDIUM..CoffeeSize.LARGE: println ‘Programmer‘ break; case CoffeeSize.MUG: println ‘Caffeine IV‘ break; } } orderCoffee(CoffeeSize.SMALL) orderCoffee(CoffeeSize.LARGE) orderCoffee(CoffeeSize.MUG) for(size in CoffeeSize.values()){ println size }
/*output Coffee order received for size SMALL:Conscious Coffee order received for size LARGE:Programmer Coffee order received for size MUG:Caffeine IV SHORT SMALL MEDIUM LARGE MUG */

2.for-each循環

def list = [1,3,6,4,9]

println ‘傳統for循環‘
for(int i = 0; i < list.size(); i++){
    println i
}


println 
‘實現了 Iterable接口的for循環‘ for(int i : list){ println i } println ‘不指定類型的for循環‘ for(i in list){ println i } /*output 傳統for循環 0 1 2 3 4 實現了 Iterable接口的for循環 1 3 6 4 9 不指定類型的for循環 1 3 6 4 9 */

3.變長參數

def receiveVarArgs(int a, int...b){
    println "$a and $b"
}

def receiveArray(int a, int[] b){
    println "$a and $b"
}

receiveVarArgs(1,2,3,4,5)

receiveArray(1,2,3,4,5)

/*output
1 and [2, 3, 4, 5]
1 and [2, 3, 4, 5]
*/

[email protected]

class Worker{
    def Work(){println ‘Work‘}
    def Analyze(){println ‘Analyze‘}
    def WriteReport(){println ‘WriteReport‘}
}

class Expert{
    def Analyze(){println ‘Expert Analyze‘}
}

class Manager{
    @Delegate Expert expert = new Expert()
    @Delegate Worker worker = new Worker()
}

def ironcrow = new Manager()
ironcrow.Work()
ironcrow.Analyze()
ironcrow.WriteReport()

/*output
Work
Expert Analyze
WriteReport

*/

[email protected]:惰性創建

// 非惰性創建
class Heavy {
    def size = 10
    Heavy(){
        println("Create Heavy with $size")
    }
}

class AsNeeded {
    def value
     Heavy heavy1 = new Heavy()
     Heavy heavy2 = new Heavy(size: value)

    AsNeeded(){
        println ‘Created AsNeeded‘
    }
}

class Program {
    static void main(String[] args){
        def asNeeded = new AsNeeded(value: 1000)
        println asNeeded.heavy1.size
        println asNeeded.heavy1.size
        println asNeeded.heavy2.size
        println asNeeded.heavy2.size
    }
}

/*output

Create Heavy with 10
Create Heavy with 10
Created AsNeeded
10
10
null
null
*/
// 惰性創建
class AsNeeded {
    def value
    @Lazy Heavy heavy1 = new Heavy()
    @Lazy Heavy heavy2 = new Heavy(size: value)

    AsNeeded(){
        println ‘Created AsNeeded‘
    }
}

/*output
Created AsNeeded
Create Heavy with 10
10
10
Create Heavy with 10
1000
1000
*/

6.@Singleton單例

@Singleton(lazy = true)
class TheUnique{
    def sayHello(){
        println ‘hello‘
    }
}

TheUnique.instance.sayHello()


/*output
hello
*/

Groovy學習筆記-Java 5新特性支持