Scenario:
Create a Redis Cache factory.
Solution:
Creational Pattern for the creation of objects. So the Factory creates the objects required so its delegating the "new" to factory from the caller.
Example: Redis Cache factory which creates the objects of RedisCacheClient based on configurations
- RedisCacheFactory and the RedisCache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 | namespace TestProject
{
public interface IRedisCache
{
void Push(Dictionary<string, string> data);
}
public class RedisCache : IRedisCache
{
public void Push(Dictionary<string, string> data)
{
// Push to Redis
}
}
public class RedisCacheFactory
{
private static readonly Dictionary<Tuple<Type, string>, IRedisCache?> _clientCache;
public RedisCacheFactory()
{
}
public static IRedisCache? GetCacheClient(Type dataType, string serviceName)
{
return InternalGetCacheClient(dataType, serviceName);
}
private static IRedisCache? InternalGetCacheClient(Type dataType, string serviceName)
{
var cacheKey = new Tuple<Type, string>(dataType, serviceName);
if (_clientCache.TryGetValue(cacheKey, out var client))
{
return client;
}
var type = (typeof(RedisCache)).MakeGenericType(dataType);
client =
(IRedisCache)
Activator.CreateInstance(type, serviceName)!;
_clientCache[cacheKey] = client;
return client;
}
}
} |
| |
- Push the Log to Redis through the client created & returned by the factory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | namespace TestProject
{
public class Caller
{
public void PushData(Dictionary<string, string> data)
{
var type = Type.GetType("TestProject.ApiLog");
var redisClient = RedisCacheFactory.GetCacheClient(type, "api");
var dictionary = new Dictionary<string, string>();
dictionary.Add("logapi", "{Request}");
redisClient.Push(dictionary);
}
}
} |
No comments:
Post a Comment