程式扎記: [ GroovyGN ] Newify to Create New Instances

標籤

2015年12月16日 星期三

[ GroovyGN ] Newify to Create New Instances

Source From Here
Introduction
The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python. If we use the @Newify annotation we get a slightly more readable piece of code (in some situations). We can use parameters in the annotation to denote all those classes we want to be instantiated with the new() method or without the new keyword.

Sample Code
  1. class Author {  
  2.     String name  
  3.     List books  
  4. }  
  5. class Book {   
  6.     String title   
  7. }  
  8.   
  9. def createKing() {  
  10.     new Author(name: 'Stephen King', books: [  
  11.         new Book(title: 'Carrie'),  
  12.         new Book(title: 'The Shining'),  
  13.         new Book(title: 'It')  
  14.     ])  
  15. }  
  16.   
  17. assert 3 == createKing().books.size()  
  18. assert 'Stephen King' == createKing().name  
  19. assert 'Carrie' == createKing().books.getAt(0).title  
  20.   
  21. @Newify([Author, Book])   
  22. def createKingRuby() {  
  23.     Author.new(name: 'Stephen King', books: [  
  24.         Book.new(title: 'Carrie'),  
  25.         Book.new(title: 'The Shining'),  
  26.         Book.new(title: 'It')  
  27.     ])  
  28. }  
  29.   
  30. assert 3 == createKingRuby().books.size()  
  31. assert 'Stephen King' == createKingRuby().name  
  32. assert 'Carrie, The Shining, It' == createKingRuby().books.title.join(', ')  
  33.   
  34. @Newify([Author, Book])   
  35. def createKingPython() {  
  36.     Author(name: 'Stephen King', books: [  
  37.         Book(title: 'Carrie'),  
  38.         Book(title: 'The Shining'),  
  39.         Book(title: 'It')  
  40.     ])  
  41. }  
  42.   
  43. assert 3 == createKingPython().books.size()  
  44. assert 'Stephen King' == createKingPython().name  
  45. assert 'It' == createKingPython().books.title.find { it == 'It' }  


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!