40 lines
885 B
C#
40 lines
885 B
C#
namespace Harmonia.Core.Caching;
|
|
|
|
public abstract class Cache<TKey, TValue> : ICache<TKey, TValue> where TKey : notnull
|
|
{
|
|
protected abstract TValue? TryGetValue(object key);
|
|
protected abstract TValue? Fetch(TKey key);
|
|
protected abstract void AddToCache(object key, TValue value);
|
|
|
|
public TValue? Get(TKey key)
|
|
{
|
|
object? actualKey = GetKey(key);
|
|
|
|
if (actualKey == null)
|
|
return default;
|
|
|
|
return TryGetValue(actualKey) ?? Refresh(key);
|
|
}
|
|
|
|
public TValue? Refresh(TKey key)
|
|
{
|
|
object? actualKey = GetKey(key);
|
|
|
|
if (actualKey == null)
|
|
return default;
|
|
|
|
TValue? value = Fetch(key);
|
|
|
|
if (value == null)
|
|
return default;
|
|
|
|
AddToCache(actualKey, value);
|
|
|
|
return value;
|
|
}
|
|
|
|
protected virtual object? GetKey(TKey key)
|
|
{
|
|
return key;
|
|
}
|
|
} |