views:

103

answers:

2

I'm learning GRASP pattern at school and I have a question about the Creator pattern.

Let's say you have three class, Computer, UserRespository and User.

One of the rules of the GRASP Creator pattern tells you to assign the responsibility of creating an object to the class containing those object. By following this guideline, UserRepository should be the creator of User.

So if Computer wants to create a user, he'll ask UserRespository.

//in Computer's code
repo.createUser("John");


//in UserRepository
public void createUser(String name)
{
    users.add(new User(name));
}

This effectively decouple Computer from User. Really?

Clearly, Computer doesn't have any reference to User, but I think Computer is still highly coupled to the creation of User. Why? The createUser method is poorly hiding the creation. If User change it's constructor, you'd have to change the createUser method to reflect those changes and also every client using the method.

What are the advantage of using this pattern then?

A: 

The decoupling arises from the fact that the repository object can be arbitrary; that is, you can choose which repository object to pass into the computer object. While there is still a CreateUser method, the source of the User data is determined by which repository object is used.

In your example, the repository object would more commonly be called the UserRepository object.

Robert Harvey
A: 

I've learned that decoupling is really asking "Can you extract this class from the system?". So by hiding the creation of an object behind a method, given this object is not used anywhere else than in the creator, it effectively decouple the object from the system.

Subb