I have used the abstract factory pattern to help with Dependency Injection and make my project more unit test friendly. A good couple of times I have come across the point that we should return objects in a ready-to-use state. Doing extra work like getting an object's state from a database makes it harder to test unless we can mock out the database layer. So I moved this into a factory. Although at this point I think it should be altered to a builder because I am not returning a family of products, there is only 1 product.
Anyway, I need to ensure that there is only 1 instance of 2 or 3 classes in my application. I did this in the factory. I am avoiding the use of the Singleton pattern because I don't like it. I think it violates OO too much and there are better ways of doing it. It also makes unit testing harding. So my factory contains the single instance of the class. If someone asks for the object I check if I have already created it and return it.
Now I need to add some more functionality. I need to be able to reset the object's state. For example we can change its configuration in the database. Now I need to get hold of that instance and change its internal state to mirror the new configuration. I am not sure if I should stick this into the factory but this seems to violate Single Responsibility Principle. The other alternative is to make an object that knows how to reset that object's state. For example:
class MyObjectResetter
{
private MyObject myObject;
private MyDao myDao;
public MyObjectResetter(MyObject myObject, MyDao myDao)
{
this.myObject = myObject;
this.myDao = myDao;
}
public void Reset()
{
myObject.Details = myDao.GetDetails();
myObject.MoreDetails = myDao.GetMoreDetails();
}
}
Are there any better ideas? Are there any better patterns?