What is Delegate ??

25 / Aug / 2012 by Amit Kumar 1 comments

Suppose a scenario, where User and Account classes are linked as below:
[groovy]
class Account {
String email
String password
// … other fields
}

class User {
Account account
String name
String address
// … other fields
}
[/groovy]

At the time of creating a new User, and accessing the user members, we write something of this sort:
[groovy]
// For initalizing the user class first we have to initializing Account class.
Account account = new Account(email:”amit.kumar@gmail.com”, password:”intelligrape”)
// Now have to pass that account instance for initializing User class
User user = new User(account:account, name:”Amit”, address:”Intelligrape City”)

// For Accessing User’s Account information we have to use “user.account” as prefix
println user.account.email
println user.account.password
[/groovy]

It can be clearly seen that we have to write “user.account” as a prefix for accessing user’s account information and have to initialize account info separately. If we use @Delegate annotation before account declaration as below:
[groovy]
@Delegate Account account = new Account()
[/groovy]

Time is saved and groovy will manage account for user automatically. We do not need to care for initializing account information separately.
[groovy]
// Initializing account information with User class.
User user = new User(email:”amit.kumar@gmail.com”, password:”intelligrape”, name:”Amit”, address:”Intelligrape City”)
// Accessing User Account info with “user” prefix only instead of “user.account” prefix
println user.email
println user.password
[/groovy]

Note: When you use @Delegate annotation, all the methods of delegated class(Account) are implement in current class(User), so we will be able to access those members with prefix (“user”) only.

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

FOUND THIS USEFUL? SHARE IT

comments (1 “What is Delegate ??”)

  1. Senthil

    Thanks for Information ,

    Can you explain , how delegate will work for Collection Object ,

    for example, User can have multiple account ,

    Thanks and Regards

    Senthil

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *