打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
观察者模式

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Car cat = new Car();
            Mouse mouse1 = new Mouse("mouse1", cat);
            Mouse mouse2 = new Mouse("mouse2", cat);
            Master master = new Master(cat);
            cat.Cry();

            Console.ReadLine();
        }
    }

  

    interface Observer //观察者的响应(针对那一个对象)
    {
        void Reaponse();
    }

    interface Subject//针对那些观察者(也就是遇到的对象)
    {
        void AimAt(Observer obs);
    }

    class Mouse : Observer
    {
        private string Name;

        public Mouse(string name, Subject sb)
        {
            this.Name = name;
            sb.AimAt(this);
        }

        public void Reaponse()
        {
            Console.WriteLine(Name + " attempt to escape!");
        }
    }

    class Master : Observer
    {
        public Master(Subject sb)
        {
            sb.AimAt(this);
        }

        public void Reaponse()
        {
            Console.WriteLine("Host waken!");
        }

    }

    class Car : Subject//这就是猫的响应和执行的对象
    {
        ArrayList arrs;
        public Car()
        {
            arrs = new ArrayList();

        }
        public void AimAt(Observer obs)//它的对象就是叫一声
        {
            arrs.Add(obs);
        }

        public void Cry()
        {
            Console.WriteLine("Cat cryed!");
            foreach (Observer lsg in this.arrs)
            {

                lsg.Reaponse();

            }
        }
    }

 


}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
一道java关于设计模式笔试题
.net面试题3
C#程序设计笔试题
C#经典笔试题
C#.Net的常见面试试题
设计模式--观察者模式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服