Let me introduce my situation:
I have Java EE application and in one package, I want to have classes which will act primarily as cache for some data from database, for example:
- class that will hold all articles for our website
- class that will hold all categories
- etc.
Every class should have some update()
method, which will update data for that class from database and also some other methods for data manipulation specific for that data type.
Now, I would like to call update()
method for all class instances (there will be exactly one class instance for every class) from one place.
What is the best design?
3
You should seriously consider using the observer pattern and, rather than calling an Update method which iterates through a list of objects that need an Update, you simply call an event to which all of your objects are subscribed for as long as they are valid to be updated?
5
While you might be tempted to create an abstract class or interface. I would strongly advise against that approach.
Reasons Against Interfaces
- You’ll end up with two classes that do a lot of the same work.
- It defines a contract but doesn’t improve cohesion of code.
Reasons Against Abstraction
- You’ll end up with 3 classes. The base class and 2 implementing classes.
- Most of the abstract methods will be public. Abstraction works best when the scope of the re-used methods are protected. This makes it clear that the abstract class is truly there to assist inherited classes.
Recommended Approach
- Define a sealed caching class that doesn’t care when it caches. Create a class called
DatabaseCacher
that knows how to keepICachable
objects in memory. Articles
andCategories
then implement theICachable
interface.
DatabaseCacher
should be used to modify the properties of ICachable
. Don’t implement any setter methods on your ICachable
objects. Instead, create a generic setter method on DatabaseCacher
that takes the name of the property as a parameter with it’s value. This allows you to localize all caching and write operations of those objects.
I would avoid using a property change event listening approach. As it creates a large number of binding between only two entities (DatabaseCacher
and ICachable
objects). Property change listeners work best when the connection is ambiguous.
4