I have first seen the decorator pattern in the IO classes. Now, I am watching a course in pluralsight, Encapsulation and SOLID, in which the course discussed another use of the decorator pattern. Here is the class diagram.
MessageStore
|
<interface>
IStoreReader
|
---------------------------------------------------------
| | |
StoreLogger StoreCache FileStore
The Message store is a class that can read from any file or database through the interface IStoreReader. Also the class has a way of caching the data return by the underlying IStoreReader (FileStore). Lastly, the whole operation of the MessageStore is being logged, before and after reading through the StoreCache. He applied decorator pattern so the classes where initialized like this:
IStoreReader fileStore = new FileStore( some arguments);
IStoreReader cache = new FileStore(fileStore);
IStoreReader storeLogger = new StoreLogger(cache);
MessageStore messageStore = new MessageStore(storeLogger);
The IStoreReader's sole method is read(int id).
The code is something like this :
StoreLogger :
public List<String> read(int id){
log.information("Reading ...");
return this.storeReader.read(id);
log.information("Done reading ...");
}
StoreCache :
public List<String> read(id){
List<String> result = this.cache.find(id);
if(result.isEmpty()){
return this.storeReader.read(id);
}
return result;
}
FileStore:
public List<String> read(id){
//implementation
}
Since MessageStore only interacts to one IStoreReader, only the instance of the StoreLogger was passed and that's the thing that's been bugging me. Isn't the solution be better if the 3 classes were passed to the MessageStore (because I believe this is somewhat a service class?) and the sole interface can be replaced by 3 more specific interfaces? Readability is another concern in this design.
Also, when I first saw how the decorator pattern is being used I noticed that its purpose is to add new value to the one that was passed; as observed in the IO like InputStream, BufferedInputStream, etc.
Please help me gain insight on this one.
Aucun commentaire:
Enregistrer un commentaire