-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShop.cs
More file actions
64 lines (54 loc) · 1.68 KB
/
Shop.cs
File metadata and controls
64 lines (54 loc) · 1.68 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
using System;
using System.Collections.Generic;
namespace DesignPatterns.Observer
{
using GoodsReminder = Dictionary<string, int>;
class Shop : IObservable<GoodsReminder>
{
readonly GoodsReminder _stock;
readonly List<IObserver<GoodsReminder>> _observers = new();
public Shop(GoodsReminder stock) => _stock = stock;
public void Register(IObserver<GoodsReminder> observer)
{
if (_observers.Contains(observer)) return;
_observers.Add(observer);
observer.Update(new GoodsReminder(_stock));
}
public void Unregister(IObserver<GoodsReminder> observer)
{
_observers.Remove(observer);
}
public void Sell(string good, int amount)
{
if (!_stock.ContainsKey(good))
{
throw new ArgumentException($"oops, we don't sell any {good}");
}
_stock[good] -= amount;
Console.WriteLine(
$"[Shop] New sale of {good}. Sale amount: {amount}, new reminder: {_stock[good]}.");
NotifyObservers();
}
public void Ship(string good, int amount)
{
if (!_stock.ContainsKey(good))
{
throw new ArgumentException($"oops, we don't sell any {good}");
}
_stock[good] += amount;
Console.WriteLine(
$"[Shop] {good[..1].ToUpper() + good[1..]} was shipped. " +
$"Shipped amount: {amount}, new reminder: {_stock[good]}.");
NotifyObservers();
}
private void NotifyObservers()
{
foreach (var observer in _observers)
{
// Copying a whole stock dictionary for every observer should be very ineffective,
// but it protects against external changes.
observer.Update(new GoodsReminder(_stock));
}
}
}
}