{"id":"6b0857af5a2625e44ecaad10","slug":"order-observer","title":"Obserwator zamówień","summary":"Zamówienie powiadamia subskrybentów o zmianie statusu; subskrypcję da się anulować, a dziennik audytu zapisuje przejścia.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["observer"],"techs":["dotnet","typescript"],"tags":["observer","events","behavioral"],"languages":[{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\npublic enum OrderStatus { New, Paid, Shipped, Delivered, Cancelled }\n\npublic interface IOrderObserver\n{\n    void OnStatusChanged(Order order, OrderStatus previous);\n}\n\npublic class Order\n{\n    public Order(int id)\n    {\n        Id = id;\n        Status = OrderStatus.New;\n    }\n\n    public int Id { get; private set; }\n    public OrderStatus Status { get; private set; }\n\n    // TODO: keep the subscribed observers\n\n    /// <summary>Subscribes an observer; disposing the result unsubscribes it.</summary>\n    public IDisposable Subscribe(IOrderObserver observer)\n    {\n        throw new NotImplementedException();\n    }\n\n    /// <summary>\n    /// Ignores an unchanged status, refuses changes after Delivered or Cancelled (InvalidOperationException),\n    /// otherwise changes the status and notifies every observer (in subscription order) with the previous status.\n    /// </summary>\n    public void ChangeStatus(OrderStatus status)\n    {\n        throw new NotImplementedException();\n    }\n}\n\npublic class AuditLog : IOrderObserver\n{\n    private readonly List<string> entries = new List<string>();\n    public IReadOnlyList<string> Entries { get { return entries; } }\n\n    public void OnStatusChanged(Order order, OrderStatus previous)\n    {\n        // TODO: add \"#<id>: <previous> -> <status>\", e.g. \"#7: New -> Paid\"\n        throw new NotImplementedException();\n    }\n}\n","testCount":6},{"lang":"typescript","runner":"browser","starter":"type OrderStatus = 'new' | 'paid' | 'shipped' | 'delivered' | 'cancelled';\n\ninterface OrderObserver {\n  onStatusChanged(order: Order, previous: OrderStatus): void;\n}\n\nclass Order {\n  status: OrderStatus = 'new';\n\n  constructor(readonly id: number) {}\n\n  // TODO: keep the subscribed observers\n\n  /** Subscribes an observer and returns a function that unsubscribes it. */\n  subscribe(observer: OrderObserver): () => void {\n    throw new Error('Not implemented');\n  }\n\n  /**\n   * Ignores an unchanged status, refuses changes after 'delivered' or 'cancelled' (throws Error),\n   * otherwise changes the status and notifies every observer (in subscription order) with the previous status.\n   */\n  changeStatus(status: OrderStatus): void {\n    throw new Error('Not implemented');\n  }\n}\n\nclass AuditLog implements OrderObserver {\n  readonly entries: string[] = [];\n\n  onStatusChanged(order: Order, previous: OrderStatus): void {\n    // TODO: push \"#<id>: <previous> -> <status>\", e.g. \"#7: new -> paid\"\n  }\n}\n","testCount":6,"tests":"function recorder(name, log) {\n  return { onStatusChanged: (order, previous) => log.push(name + ':' + previous + '->' + order.status) };\n}\n\ntest('notifies a subscribed observer', () => {\n  const log = [];\n  const order = new Order(1);\n  order.subscribe(recorder('a', log));\n  order.changeStatus('paid');\n  expect(log).toEqual(['a:new->paid']);\n});\n\ntest('notifies observers in subscription order', () => {\n  const log = [];\n  const order = new Order(2);\n  order.subscribe(recorder('first', log));\n  order.subscribe(recorder('second', log));\n  order.changeStatus('paid');\n  expect(log).toEqual(['first:new->paid', 'second:new->paid']);\n});\n\ntest('the returned function unsubscribes', () => {\n  const log = [];\n  const order = new Order(3);\n  const unsubscribe = order.subscribe(recorder('a', log));\n  unsubscribe();\n  order.changeStatus('paid');\n  expect(log).toHaveLength(0);\n});\n\ntest('an unchanged status does not notify', () => {\n  const log = [];\n  const order = new Order(4);\n  order.subscribe(recorder('a', log));\n  order.changeStatus('new');\n  expect(log).toHaveLength(0);\n});\n\ntest('AuditLog records transitions', () => {\n  const order = new Order(7);\n  const audit = new AuditLog();\n  order.subscribe(audit);\n  order.changeStatus('paid');\n  order.changeStatus('shipped');\n  expect(audit.entries).toEqual(['#7: new -> paid', '#7: paid -> shipped']);\n});\n\ntest('a final status cannot change', () => {\n  const order = new Order(8);\n  order.changeStatus('cancelled');\n  expect(() => order.changeStatus('paid')).toThrow();\n  expect(order.status).toBe('cancelled');\n});\n"}],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.864Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Gdy zmienia się status zamówienia, kilka części systemu musi zareagować (e-mail do klienta, magazyn, audyt). Zamówienie nie powinno ich znać – wystarczy, że "},{"type":"text","text":"powiadomi obserwatorów","marks":[{"type":"bold"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Subscribe","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"subscribe","marks":[{"type":"code"}]},{"type":"text","text":" dodaje obserwatora i zwraca uchwyt anulowania ("},{"type":"text","text":"IDisposable","marks":[{"type":"code"}]},{"type":"text","text":" w C#, funkcję w TypeScript)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ChangeStatus","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"changeStatus","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ten sam status → nic się nie dzieje (brak powiadomień),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"po "},{"type":"text","text":"Delivered","marks":[{"type":"code"}]},{"type":"text","text":" lub "},{"type":"text","text":"Cancelled","marks":[{"type":"code"}]},{"type":"text","text":" zmiana jest zabroniona ("},{"type":"text","text":"InvalidOperationException","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Error","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"w innym przypadku zmienia status i powiadamia "},{"type":"text","text":"wszystkich","marks":[{"type":"bold"}]},{"type":"text","text":" obserwatorów w kolejności subskrypcji, przekazując poprzedni status."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"AuditLog","marks":[{"type":"code"}]},{"type":"text","text":" zapisuje wpisy w formacie "},{"type":"text","text":"#7: New -> Paid","marks":[{"type":"code"}]},{"type":"text","text":" (w TypeScript: "},{"type":"text","text":"#7: new -> paid","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]}]},{"type":"callout","attrs":{"variant":"info","title":"Uruchamianie"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wersja C# jest sprawdzana na serwerze (Judge0), wersja TypeScript – w przeglądarce."}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"exercism","url":"https://exercism.org/tracks/typescript/exercises/react","title":"Exercism · TypeScript · React (reactive cells)","difficulty":"hard"},{"provider":"exercism","url":"https://exercism.org/tracks/csharp/exercises/react","title":"Exercism · C# · React (reactive cells)","difficulty":"hard"}],"articles":[{"id":"6b08bd3c80884893657cc9dd","slug":"observer","title":"Obserwator (Observer): powiadom wszystkich, nie znając nikogo"}],"topicsInfo":[{"slug":"observer","title":"Obserwator","group":"behavioral","icon":"eye"}],"author":{"id":"6b0857a15a2625e44ecaabec","name":"Anna Autorka","avatar":"/api/files/6b0857ec5a2625e44ecab0c6","handle":"anna-autorka","community":true},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-26T16:00:47.865Z","updatedAt":"2026-11-26T16:01:49.698Z"}