Singleton design & new objects inside it
In a specific scenario here,
I have a manger called UserManger used to handle CRUD for user
This manager is "Singleton" and correct by design.
But in update method I have logic
public User update (User u)
{
// This line is problematic?
User u1 = n开发者_如何学编程ew User();
copy(u,u1);
//Some logic
dao.update(u);
}
Will creating any new objects in singleton manager problematic? Especially for a very concurrent system.
Will
public User update (User u, User u1)
{
copy(u,u1);
//Some logic
dao.update(u);
}
Solve my problem?
Just creating an object within a singleton method won't cause any problems. You're not sharing any state between threads, after all.
You would have potential problems if you had state within the singleton itself - but all you've shown is creating a local variable, not changing an instance variable. Each invocation of a method has its own entirely separate set of local variables. Two threads can both be executing the same method, but they won't see each other's local variables.
No. But if you put
User u1;
as a global variable, It will cause issue.
But I have a question, why dont you code this way?
public User update (User u)
{
//Some logic
User u = dao.update(u);
return u;
// OR return dao.update(u);
}
You don't need to copy here. Do a copy will need memory allocated 2 times more for User object in this method.
Without understanding your system, I have to call in to question the design patterns described here. Both Singleton and SomethingManager are anti-patterns.
You may just need to consider a more descriptive name for UserManager
, but I would highly recommend using an IoC framework like Spring to inject it where it is required rather than nailing it down as a 'global' (which is essentially what a singleton is).
精彩评论