당신은하지 굳이 용 (인터페이스가 필요 변경된 이벤트에 가입하고자하는 다른 클래스에서 다음
// Specifies the signature for the event and stores the reference
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class ObservableObject
{
// Creates an event called Changed using the signature provided by the
// delegate.
public event ChangedEventHandler Changed;
// This is the method we're interested in notifying subscribers about.
public void SomeInterestnigMethod()
{
// Something just changed, notify subscribers
Changed(this, new EventArgs());
}
}
그리고 예를 들어 java/C#와 같은 인터페이스 키워드 감각)을 관찰자에게 전달해야합니다. 에 알릴 필요가있을 때 어떤 방법으로 호출해야하는지 알 필요가 있습니다. 옵서버는 관심사를 등록하고 목록에 추가합니다.
알림을받을 때마다 관찰자 목록을 통해 메서드를 호출합니다. 누군가가 더 이상 통보를 받고 싶지 않다면, 관찰자 목록에서 제거하는 것입니다.
using System;
using System.Collections.Generic;
namespace ObserverTest
{
interface IInvestor
{
void Update(Stock stock);
}
abstract class Stock
{
private string _symbol;
private double _price;
private List<IInvestor> _investors = new List<IInvestor>();
// Constructor
public Stock(string symbol, double price)
{
this._symbol = symbol;
this._price = price;
}
public void Attach(IInvestor investor)
{
_investors.Add(investor);
}
public void Detach(IInvestor investor)
{
_investors.Remove(investor);
}
public void Notify()
{
foreach (IInvestor investor in _investors)
{
investor.Update(this);
}
Console.WriteLine("");
}
public double Price
{
get { return _price; }
set
{
if (_price != value)
{
_price = value;
Notify();
}
}
}
public string Symbol
{
get { return _symbol; }
}
}
class IBM : Stock
{
public IBM(string symbol, double price)
: base(symbol, price)
{
}
}
class Investor : IInvestor
{
private string _name;
// Constructor
public Investor(string name)
{
this._name = name;
}
public void Update(Stock stock)
{
Console.WriteLine("Notified {0} of {1}'s " +
"change to {2:C}", _name, stock.Symbol, stock.Price);
}
}
class MainApp
{
static void Main()
{
IBM ibm = new IBM("IBM", 120.00);
ibm.Attach(new Investor("Sorros"));
ibm.Attach(new Investor("Berkshire"));
ibm.Price = 120.10;
ibm.Price = 121.00;
ibm.Price = 120.50;
ibm.Price = 120.75;
Console.ReadKey();
}
}
}
출처
2010-04-21 18:25:20
nos
어떤 언어에있는 경우 더 많은 정보를 읽어야 훌륭한 article on events in .Net이있다? – bmargulies
정말 중요하지 않습니다. – Malfist