-
Notifications
You must be signed in to change notification settings - Fork 0
/
Observer.cs
89 lines (76 loc) · 1.92 KB
/
Observer.cs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
namespace Observer
{
// СМОТРЯЩИЙ
public interface IObserver
{
void Update();
}
// ОБОЗРИМЫЙ
public interface IObservable
{
void AddObserver(IObserver observer);
void RemoveObserver(IObserver observer);
void NotifyObservers();
}
public class NotificationCenter: IObservable
{
public List<IObserver> Observers { get; private set; }
public NotificationCenter()
{
Observers = new List<IObserver>();
}
public void AddObserver(IObserver observer)
{
if (observer == null)
{
throw new NullReferenceException(nameof(observer));
}
Observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
if (observer == null)
{
throw new NullReferenceException(nameof(observer));
}
Observers.Remove(observer);
}
public void NotifyObservers()
{
foreach(IObserver observer in Observers)
{
observer.Update();
}
}
}
class Card: IObserver
{
public int Number { get; private set; }
public bool IsSwiped { get; private set; }
public Card(int number)
{
Number = number;
IsSwiped = false;
}
public void Swipe(int swipeDirection)
{
if (swipeDirection >= 0)
{
IsSwiped = true;
}
}
public void Update()
{
if (IsSwiped == true)
{
Console.WriteLine($"Card#{Number} has swiped!");
}
else
{
Console.WriteLine($"Card#{Number} hasn't swiped!");
}
}
}
}