2012-09-29 57 views
2

我想學習如何創建簡單的groovy類,這不是域類。我想在我的軟件中創建一組類(及其對象),但無意保存到數據庫。具體來說,我有一個關於如何創建一個屬性是第二類的列表的類的問題。像這樣:創建groovy類

class oParent{ 
    def fName 
    def lName 
    def listOfChildren 
} 
class oChild{ 
    def propertyOne 
    def propertyTwo 
} 

所以,用這個例子,我可以創造這樣每一個對象:

def p = new oParent(); 
def cOne = new oChild(); 
def cTwo = new oChild(); 

p.fName ="SomeName" 
p.lName ="some Last Name" 

cOne.propertyOne = "a" 
cOne.propertyTwo = "b" 

cTwo.propertyOne = "c" 
cTwo.propertyTwo = "d" 

那麼,如何添加每個子對象(錐CTWO)至父對象p)。一旦添加,我將如何遍歷父類的子元素屬性,例如,打印所有子類的所有propertyTwo屬性?

+0

任何特別的理由下來票呢? – jason

+0

也許是因爲奇怪的類和實例名稱。一種輕描淡寫的理由,但你永遠不知道。 –

回答

0

好吧,事實證明,這很簡單,除非我做錯了。這是我如何做的:

class oParent{ 
    def fName 
    def lName 
    def listOfChildren = [] 
} 

class oChild{ 
    def propertyOne 
    def propertyTwo 
} 

def p = new oParent(); 
def cOne = new oChild(); 
def cTwo = new oChild(); 

p.fName ="SomeName" 
p.lName ="some Last Name" 

cOne.propertyOne = "a" 
cOne.propertyTwo = "b" 

cTwo.propertyOne = "c" 
cTwo.propertyTwo = "d" 

p.listOfChildren.add(cOne) 
p.listOfChildren.add(cTwo) 

我可以迭代這樣的:

p.listOfChildren.each{ foo-> 
    log.debug(foo.propertyOne) 
} 
+1

你是對的。把它命名爲兒童比列出兒童更典型,但這個想法是一樣的。 – erturne

+1

給oParent(通常命名爲'Parent')也是更典型,它是一個addChild方法,而不是直接訪問父級列表。 – GreyBeardedGeek

4

這是你的代碼中的註釋版本更改一些建議:

// 1) Class names start with a Capital Letter 
class Parent { 

    // 2) If you know the type of something, use it rather than def 
    String fName 
    String lName 

    // 3) better name and type 
    List<Child> children = [] 

    // 4) A utility method for adding a child (as it is a standard operation) 
    void addChild(Child c) { 
    children << c 
    } 

    // 5) A helper method so we can do `parent << child` as a shortcut 
    Parent leftShift(Child c) { 
    addChild(c) 
    this 
    } 

    // 6) Nice String representation of the object 
    String toString() { 
    "$fName, $lName $children" 
    } 
} 

// See 1) 
class Child{ 

    // See 2) 
    String propertyOne 
    String propertyTwo 

    // See 6) 
    String toString() { 
    "($propertyOne $propertyTwo)" 
    } 
} 

// Create the object and set its props in a single statement 
Parent p = new Parent(fName: 'SomeName', lName:'some Last Name') 

// Same for the child objects 
Child cOne = new Child(propertyOne: 'a', propertyTwo: 'b') 
Child cTwo = new Child(propertyOne: 'c', propertyTwo: 'd') 

// Add cOne and cTwo to p using the leftShift helper in (5) above 
p << cOne << cTwo 

// prints "SomeName, some Last Name [(a b), (c d)]" 
println p 

然後,你可以這樣做:

println p.children.propertyTwo // prints "[b, d]" 

或者這樣:

p.children.propertyTwo.each { println it } // prints b and d on separate lines 

,或者更確切地說是:

p.children.each { println it.propertyTwo } // As above