Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't see much difference here in my C# version.</p> <p>I think the author of mentioned C# book might try to make his example looks like the original Observer pattern, where there are <code>Subject</code>, <code>ConcreteSubject</code>, <code>Observer</code>, and <code>ConcreteObserver</code> classes. These are actually unnecessary in many conditions. Many times, just subscribe to the event with method is enough.</p> <p>By using event and delegate C# has provided, you can eliminate the need to maintain "observer list" and its related attach/detach methods yourself. They also provide an easy way to notify the subscribed clients of new event.</p> <p><strong>Update:</strong> Just saw @Tomas's implementation. He has good use of C# 3 there. However, if you want to see direct mapping from Ruby code my example below could help.</p> <pre><code>using System; namespace Observer { class Program { static void Main() { Employee fred = new Employee() { Name = "Fred", Title = "Crane Operator", Salary = 40000.0 }; TaxMan tax_man = new TaxMan(); fred.Update += tax_man.OnUpdate; fred.Salary = 50000.0; } } public class Subject { public delegate void UpdateHandler(Subject s); public virtual event UpdateHandler Update; } public class Employee : Subject { public string Name { get; set; } public string Title { get; set; } private double _salary; public double Salary { get { return _salary; } set { _salary = value; if (Update != null) Update(this); } } public override event UpdateHandler Update; } public class TaxMan { public void OnUpdate(Subject s) { if (s is Employee) Console.WriteLine("Send {0} a new tax bill!", (s as Employee).Name); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload