Created
August 7, 2013 09:28
-
-
Save yemrekeskin/6172574 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//interface the all observer classes should implement | |
public interface IObserver<TObject> | |
{ | |
void Notify(TObject obj); | |
} | |
//interface that all observable classes should implement | |
public interface IObservable<TObject> | |
{ | |
void Register(IObserver<TObject> observer); | |
void UnRegister(IObserver<TObject> observer); | |
void Notify(TObject obj); | |
} | |
public class ObservableImpl<TObject> | |
: IObservable<TObject> | |
{ | |
protected readonly List<IObserver<TObject>> _list = null; | |
public ObservableImpl() | |
{ | |
_list = new List<IObserver<TObject>>(); | |
} | |
public void Register(IObserver<TObject> observer) | |
{ | |
if (!_list.Contains(observer)) | |
_list.Add(observer); | |
} | |
public void UnRegister(IObserver<TObject> observer) | |
{ | |
if (_list.Contains(observer)) | |
_list.Remove(observer); | |
} | |
public void Notify(TObject obj) | |
{ | |
foreach (IObserver<TObject> item in _list) | |
item.Notify(obj); | |
} | |
} | |
public class Stock | |
:ObservableImpl<long> | |
{ | |
private long price; | |
public long Price | |
{ | |
get { return price; } | |
set | |
{ | |
price = value; | |
base.Notify(price); | |
} | |
} | |
} | |
public class StockMonitor | |
: IObserver<long> | |
{ | |
public void Notify(long obj) | |
{ | |
Console.WriteLine(obj); | |
} | |
} | |
// using structure | |
public class MainClass | |
{ | |
public static void Main() | |
{ | |
StockMonitor stockDisplay = new StockMonitor(); | |
Stock stock = new Stock(); | |
stock.Register(stockDisplay); | |
//loop 100 times and modify the ask price | |
for (int looper = 0; looper < 100; looper++) | |
{ | |
stock.Price = looper; | |
if (looper == 10) stock.UnRegister(stockDisplay); // for example | |
} | |
//unregister the display | |
stock.UnRegister(stockDisplay); | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment