-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeyValueDataBase.cs
More file actions
executable file
·68 lines (52 loc) · 1.95 KB
/
KeyValueDataBase.cs
File metadata and controls
executable file
·68 lines (52 loc) · 1.95 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
namespace CleverCrow.Fluid.Databases {
public interface IKeyValueData<V> {
V Get (string key, V defaultValue = default);
void Set (string key, V value);
bool Has (string key);
void AddKeyListener (string key, Action<V> callback);
void RemoveKeyListener (string test, Action<V> callback);
void Clear ();
string Save ();
void Load (string save);
}
public abstract class KeyValueDataBase<V> : IKeyValueData<V> {
private readonly Dictionary<string, List<Action<V>>> _callbacks = new Dictionary<string, List<Action<V>>>();
protected Dictionary<string, V> _data = new Dictionary<string, V>();
public void Set (string key, V value) {
if (string.IsNullOrEmpty(key)) {
return;
}
_data[key] = value;
if (!_callbacks.TryGetValue(key, out var callbacks)) return;
foreach (var callback in callbacks) {
callback.Invoke(value);
}
}
public bool Has (string key) {
return _data.ContainsKey(key);
}
public V Get (string key, V defaultValue = default) {
if (string.IsNullOrEmpty(key) || !_data.ContainsKey(key)) {
return defaultValue;
}
return _data[key];
}
public void Clear () {
_data.Clear();
}
public abstract string Save ();
public abstract void Load (string save);
public void AddKeyListener (string key, Action<V> callback) {
if (!_callbacks.TryGetValue(key, out var list)) {
list = new List<Action<V>>();
_callbacks[key] = list;
}
_callbacks[key].Add(callback);
}
public void RemoveKeyListener (string key, Action<V> callback) {
_callbacks[key].Remove(callback);
}
}
}