|
| 1 | +namespace Observer |
| 2 | +{ |
| 3 | + public class Ticket |
| 4 | + { |
| 5 | + public int MovieId { get; private set; } |
| 6 | + public int Amount { get; private set; } |
| 7 | + |
| 8 | + public Ticket(int movieId, int amount) |
| 9 | + { |
| 10 | + MovieId = movieId; |
| 11 | + Amount = amount; |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// Subject |
| 17 | + /// </summary> |
| 18 | + |
| 19 | + public abstract class TicketChangeNotifier { |
| 20 | + private List<ITicketChagneListener> _observers = []; |
| 21 | + |
| 22 | + public void AddObserver(ITicketChagneListener observer) { |
| 23 | + _observers.Add(observer); |
| 24 | + } |
| 25 | + |
| 26 | + public void RemoveObserver(ITicketChagneListener observer) { |
| 27 | + _observers.Remove(observer); |
| 28 | + } |
| 29 | + |
| 30 | + public void NotifyObservers(Ticket ticket) { |
| 31 | + foreach (var observer in _observers) { |
| 32 | + observer.OnTicketChange(ticket); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Observer |
| 39 | + /// </summary> |
| 40 | + public interface ITicketChagneListener { |
| 41 | + void OnTicketChange(Ticket ticket); |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Concrete Subject |
| 46 | + /// </summary> |
| 47 | + |
| 48 | + public class OrderService : TicketChangeNotifier { |
| 49 | + public void PlaceOrder(int movieId, int amount) { |
| 50 | + Console.WriteLine($"{nameof(OrderService)} is changing its state."); |
| 51 | + var ticket = new Ticket(movieId, amount); |
| 52 | + Console.WriteLine($"{nameof(OrderService)} is notifying observers..."); |
| 53 | + NotifyObservers(ticket); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// <summary> |
| 58 | + /// Concrete Observer 1 |
| 59 | + /// </summary> |
| 60 | + |
| 61 | + public class TicketResellerService : ITicketChagneListener { |
| 62 | + public void OnTicketChange(Ticket ticket) { |
| 63 | + Console.WriteLine($"{nameof(TicketResellerService)} received a new ticket: {ticket.MovieId} - {ticket.Amount}"); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + /// <summary> |
| 68 | + /// Concrete Observer 2 |
| 69 | + /// </summary> |
| 70 | + |
| 71 | + public class TicketStockService : ITicketChagneListener { |
| 72 | + public void OnTicketChange(Ticket ticket) { |
| 73 | + Console.WriteLine($"{nameof(TicketStockService)} received a new ticket: {ticket.MovieId} - {ticket.Amount}"); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments