Using a factory in an domain model object?
Scenario:
In my application (which utilises an rich domain model, where the logic is in the model, not in the services) I have users. I create new users with a service
User newUser = userService.createNewUser("Hans Dampf");
or get th开发者_开发知识库em from the database
User oldUser = userDao.findByName("Hans Dampf");
Because in every call into my application I have direct access to an user object, I would like to use the user object as an entry point into my domain model.
Each user can have different types of Galleries, saved in an other table.
class User {
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private Set<Gallery> automatic = new HashSet<Gallery>();
}
I want to have a simple way to enable a specific gallery. So my API would look like:
User user = ... // creating or retriving user
user.enableMainGallery();
Inside this method it would be necassary to create a new gallery object and add it to the list of galleries. But how to create this new instance? Using a factory? That would require to inject the factory into the domain object (may be problematic).
public void enableAutomaticGallery() {
automatic.add(automaticFactory.createAutomaticGallery(this));
}
Or is my interface definition flawed? Should I define it in some other way, such that I don't have to inject the factory? How?
As you say, the domain objects should not be made dependent on application-level objects such as factories or Daos.
The domain is typically :
- complex-enough with the functional needs, without adding other concerns (such as persistence, validation, GUI etc...)
- central and used everywhere (so it's complexity damages your productivity in many coding activities)
- reusable across related applications, and in all layers, can even be serialized and send to a different JVM on a client or a WebService (unless it has dependencies on application-level objects)
So your enableAutomaticGallery
method should be on a Service object.
It can have the same code, but will be application-dependent.
Your domain model should know nothing about any service or DAO layers or even any factory objects.
I would suggest instead of a method User.enableMainGallery()
which needs to add Gallery
objects to the instance collection (as you've said), that you instead expose a method User.addGallery(Gallery)
.
This way, the classes responsible for "enabling the gallery" do so by adding objects to the list collection.
In other words, I don't believe that the User
object should be responsible for knowing what it means to "enable a main gallery". This sounds like something that falls under the umbrealla of business logic (ambiguous term, I know).
精彩评论