vendredi 9 février 2018

Pattern to abstract cache and persistence layers

I'm trying to find a smart way to abstract the cache and the persistence layer in a JAVA application.

Let's suppose I have to look for Cars, somewhere, and I have an interface for such a usecase.

public interface Cars {
  Car getCar(String brand, String model);
}

Then I have an implementation where the persistence layer is SQLite based, but I could have other implementations in the future.

public class CarsSQLITE implements Cars {
  @Override
  Car getCar(String brand, String model) { /* Got get it in SQLITE */}
}

This is the current design of my application - that I'd prefer not to disrupt too much - on top of which I'd like to implement a persistence-agnostic in-memory cache layer.

This is what I came out with (kind of reminds me of the composite pattern).

public class CachedCars<PersistentImpl> implements Cars {
  @Inject
  private PersistentImpl persistentImpl;

  private Map<Key, SSREntity> cache=
        new ConcurrentHashMap<Key, Car>(10000);

  @Override
  Car getCar(String brand, String model) { 
    /* If Key (which encapsulates both brandh and model) 
       not in map call persistentImpl.getCar(brand,model) */
  }
}

Usage would obviously be something like

CachedCars<CarsSQLITE> cars = new CachedCars<CarsSQLITE>();
cars.getCar("BMW", "M3")

Does this make any sense ? It does answer my needs, just wondering if a smarter way (or a pattern which would fit just right) to achieve the exact same flexibility exists.

Aucun commentaire:

Enregistrer un commentaire