【设计模式】之 Observer 观察者模式

本文介绍了一种使用C#实现的观察者模式,该模式允许股票价格变动时通知所有已注册的投资者。通过具体实例展示了如何添加、删除投资者并更新他们关于特定股票价格变化的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace DesignFactory.Observer
{
    /// <summary>
    /// 观察者模式
    /// </summary>
    class Observerpattern
    {
    }

    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
    {
        public IBM(string symbol, double price) : base(symbol, price) { }
    }

    interface IInvestor
    {

        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("Notified investor {0} of {1}'s change to {2:C}", name, stock.Symbol, stock.Price);
        }

        public Stock Stock
        {
            get { return stock; }
            set { stock = value; }

        }
    }

    public class ObserverApp
    {
        public static void Main(string[] args)
        {
            Investor s = new Investor("Sorros");
            Investor b = new Investor("Berkshire");


            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;
        }
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值