2

ドメインクラスではない単純なGroovyクラスを作成する方法を学ぼうとしています。ソフトウェアで一連のクラス(およびそれらのオブジェクト)を作成したいのですが、データベースに保存するつもりはありません。具体的には、2番目のクラスのリストであるプロパティを持つクラスを作成する方法について質問があります。このような:

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"

したがって、各子オブジェクト(cOneおよびcTwo)を親オブジェクトp)に追加するにはどうすればよいですか。追加したら、親クラスの子のプロパティをトラバースして、たとえば、すべての子クラスのすべてのpropertyTwoプロパティを出力するにはどうすればよいですか?

4

2 に答える 2

6

これがあなたのコードのコメントされたバージョンであり、変更のためのいくつかの提案があります:

// 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
于 2012-10-01T08:52:43.790 に答える
1

まあ、私が間違っていない限り、それはかなり単純であることがわかりました。これが私がそれをした方法です:

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)
}
于 2012-09-29T22:05:51.223 に答える