看美女想到的
当男士看到美丽少妇[Belle]时,或多或少会心[Heart]跳加快,脑袋[Brain]浮想连篇。这好像就是Observer模式了吧。
实现代码[简单的一个实现]
.
using System.Collections;
using System.Collections.Generic;
using System;
public class Belle:ISubject
{
List<IObserver> _list = new List<IObserver>();
public override void Appear()
{
//Notify
Notify();
}
public override void AddObserver(IObserver observer)
{
_list.Add(observer);
}
public override void RemoveObserver(IObserver observer)
{
_list.Remove( observer);
}
public override void Notify()
{
foreach (IObserver observer in _list)
{
observer.Update("By Roboth");
}
}
}
public abstract class ISubject
{
public virtual void Appear()
{
///..
}
public abstract void AddObserver(IObserver observer);
public abstract void RemoveObserver(IObserver observer);
public virtual void Notify()
{
//..
}
}
public interface IObserver
{
void Update(string message);
}
public class Heart:IObserver
{
private string _name;
public Heart(string name)
{
this._name = name;
}
IObserver 成员
}
public class Brain:IObserver
{
private string _name;
public Brain(string name)
{
this._name = name;
}
IObserver 成员
}
class App
{
static void Main()
{
ISubject subject = new Belle();
subject.AddObserver(new Heart("my heart"));
subject.AddObserver(new Brain("my brain"));
subject.Appear();
Console.Read();
}
}
using System.Collections.Generic;
using System;
public class Belle:ISubject
{
List<IObserver> _list = new List<IObserver>();
public override void Appear()
{
//Notify
Notify();
}
public override void AddObserver(IObserver observer)
{
_list.Add(observer);
}
public override void RemoveObserver(IObserver observer)
{
_list.Remove( observer);
}
public override void Notify()
{
foreach (IObserver observer in _list)
{
observer.Update("By Roboth");
}
}
}
public abstract class ISubject
{
public virtual void Appear()
{
///..
}
public abstract void AddObserver(IObserver observer);
public abstract void RemoveObserver(IObserver observer);
public virtual void Notify()
{
//..
}
}
public interface IObserver
{
void Update(string message);
}
public class Heart:IObserver
{
private string _name;
public Heart(string name)
{
this._name = name;
}
IObserver 成员
}
public class Brain:IObserver
{
private string _name;
public Brain(string name)
{
this._name = name;
}
IObserver 成员
}
class App
{
static void Main()
{
ISubject subject = new Belle();
subject.AddObserver(new Heart("my heart"));
subject.AddObserver(new Brain("my brain"));
subject.Appear();
Console.Read();
}
}