What is Delegate ??

25 / Aug / 2012 by Amit Kumar 1 comments

Suppose a scenario, where User and Account classes are linked as below:

class Account {
    String email
    String password
    // ... other fields
}

class User {
    Account account
    String name
    String address
    // ... other fields
}

At the time of creating a new User, and accessing the user members, we write something of this sort:

// 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

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:

 @Delegate Account account = new Account()

Time is saved and groovy will manage account for user automatically. We do not need to care for initializing account information separately.

// 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

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 comment -