首页 > 其他 > 详细

两种简单发布-订阅模式写法

时间:2017-04-24 11:18:46      阅读:245      评论:0      收藏:0      [点我收藏+]

1使用委托

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

namespace _01发布订阅_委托实现_
{
   class Program
       {
            static void Main(string[] args)
                    {
Boss lee = new Boss();
Jober1 j1 = new Jober1();
Jober2 j2 = new Jober2();
lee.update1 += j1.A;
lee.update1 += j2.B;
lee.Notice();
Console.ReadKey();
}
}

//定义一个委托类型
public delegate void Notify();

//发布类
public class Boss
{
public string Name { get; set; }

public Notify update1;

public void Notice()
{
update1();
}
}

//订阅类1
public class Jober1
{
public void A()
{
Console.WriteLine("I am A");
}
}
//订阅类2
public class Jober2
{
public void B()
{
Console.WriteLine("i AM B");
}
}

}

2不使用委托

 

 

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

namespace _01发布订阅
{
class Program
{
static void Main(string[] args)
{
List<Mouth> list1=new List<Mouth>();
Cat cat1 = new Cat("Black", list1);
Mouth mouth1 = new Mouth("Tiom");
Mouth mouth2 = new Mouth("3A");
cat1.AddMouth(mouth1);
cat1.AddMouth(mouth2);
cat1.TalkStupid();
Console.ReadKey();
}
}

 

//法布雷

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

namespace _01发布订阅
{
class Cat
{
public string Name
{
get;
set;
}
public List<Mouth> list1
{
get;
set;
}
public void AddMouth(Mouth mouth)
{
this.list1.Add(mouth);
}
public void TalkStupid()
{
Console.WriteLine("My name is "+this.Name);
foreach (var item in list1)
{
item.Run();
}
}

public Cat()
{
}

public Cat(string name,List<Mouth>list)
{
this.Name = name;
this.list1 = list;
}

}
}

 

//订阅类

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

namespace _01发布订阅
{
class Mouth
{
public string Name
{
get;
set;
}

public void Run()
{
Console.WriteLine("runrunrun,MyNAMEIS "+this.Name);
}

public Mouth() { }
public Mouth(string name)
{
this.Name = name;
}
}
}

 

两种简单发布-订阅模式写法

原文:http://www.cnblogs.com/summer-fewcode/p/6755518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!