首页 > 代码库 > 两种简单发布-订阅模式写法

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

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

 

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