Design Pattern: Cache and Context

A question about a design pattern.

I have a DataManager that uses a cache DataCache that is valid for a given context (in my case, a date).

Should my DataCache store the context under which the data cached is valid, or is it better to leave it only up to the DataManager to know when the DataCache needs to be reset? I feel that having the Context in the Cache as well means more unnecessary maintenance, but maybe there is a good reason to have it in there.

A small point, but wondering what best practice would be here.

Example:

public class DataManager {
    DateTime context;
    DataCache cache;
}

public class DataCache {
    Dictionary dict;
}

or

public class DataManager {
    DateTime context;
    DataCache cache;
}

public class DataCache {
    DateTime context;  // note that we store the context here as well
    Dictionary dict;
}

If DataCache can use the context internally to know it's invalid or reset itself or whatever, it should store it. The design priority here is to keep things simpler and safer for the users of a class (here the DataCache class), rather than reduce the internal work for the class.

Depending on the way the context is used, it can be stored only in the DataCache and the DataManager can access it with a getter.


It's cache's responsibility to invalidate data when it's expired, so ideally data cahe should keep track of context and invalidate. DataManager should query the Cache and if cache does not have data it should fetch data and update the cache.


Context can be part of Cache if Context does not exists without DataCache .

You are creating dependencies between DataManager and DataCache .

Replace DataCache with interface IDataCache so that you provide loose coupling. You can change Cache implementation in future with different class.

Have a look at these SE questions:

What is dependency injection?

Inversion of Control vs Dependency Injection

链接地址: http://www.djcxy.com/p/82198.html

上一篇: 使用两个组件的“插件”类型逻辑

下一篇: 设计模式:缓存和上下文