📄 class1.cs
字号:
using System;
using System.Collections;
//被观察对象--个股
abstract class Stock
{
protected string symbol;
protected double price;
private ArrayList investors = new ArrayList();
public Stock( string symbol, double price )
{
this.symbol = symbol;
this.price = price;
}
//附加要通知的投资者
public void Attach( Investor investor )
{
investors.Add( investor );
}
//分离要通知的投资者
public void Detach( Investor investor )
{
investors.Remove( investor );
}
//通知所需要知会的投资者
public void Notify()
{
foreach( Investor i in investors )
i.Update( this );
}
//股价
public double Price
{
get{ return price; }
set
{
price = value;
Notify(); }
}
//个股标志
public string Symbol
{
get{ return symbol; }
set{ symbol = value; }
}
}
//具体被观察对象
class IBM : Stock
{
// Constructor
public IBM( string symbol, double price )
: base( symbol, price ) {}
}
//观察者
interface IInvestor
{
// Methods
void Update( Stock stock );
}
//具体观察者
class Investor : IInvestor
{
private string name;
private string observerState;
private Stock stock;
public Investor( string name )
{
this.name = name;
}
public void Update( Stock stock )
{
Console.WriteLine( "通知到股民 {0} {1}最新股价为: {2:C}", name, stock.Symbol, stock.Price );
}
// Properties
public Stock Stock
{
get{ return stock; }
set{ stock = value; }
}
}
/// <summary>
/// ObserverApp test
/// </summary>
public class ObserverApp
{
public static void Main( string[] args )
{
//创建股民
Investor s = new Investor( "张三" );
Investor b = new Investor( "李四" );
//创建个股IBM并且附加上投资的股民
IBM ibm = new IBM( "IBM", 120.00 );
ibm.Attach( s );
ibm.Attach( b );
//变更股价,其投资的所有股民都得到知会
ibm.Price = 120.10;
ibm.Price = 121.00;
ibm.Price = 120.50;
ibm.Price = 120.75;
Console.Read();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -