Java Reference
In-Depth Information
}
public void persistUser(User user) {
udr.save(user);
}
}
LISTING 5‐2:
UserDataRepository interface
package com.devchronicale.di;
public interface UserDataRepository {
public void save(User user);
}
LISTING 5‐3:
Concrete implementation of the UserDataRepository
package com.devchronicale.di;
public class UserDataRepositoryImpl implements UserDataRepository {
@Override
public void save(User user) {
// Persistence code here
}
}
LISTING 5‐4:
User class
package com.devchronicale.di;
public class User {
// User Specific Code Here
}
In Listing 5‐1, the
UserService
class provides business logic services for user management, such as
persisting the user to the database. In this example, the object creation is done in the constructor.
This couples the business logic (the class's behavior) to the object creation.
You'll refactor this example by taking the object creation out of your class and putting it in a factory.
In Listing 5‐5, an implementation of the
UserDataRepository
is created and passed to the
constructor of the
UserService
class. You change the constructor of the
UserService
class to accept
this new parameter.
LISTING 5‐5:
UserServiceFactory that creates UserService objects
package com.devchronicale.di;
public class UserServiceFactory {
public UserService getInstance(){
return new UserService(new UserDataRepositoryImpl());
}
}