会议室状态订阅(发布-订阅模式)
发布者接口
public interface IMeetingRoom { void AddPerson(IPerson person); void RemovePerson(IPerson person); void NotifyPerson(); }
订阅者接口
public interface IPerson {
void SubscibeMeetingRoom(); void CancleSubscibeMeetingRoom(); void PrintMeetingRoomMessage(string meetingRoomPublishMessage); }
发布者实现
public class MeetingRoom : IMeetingRoom { private List<IPerson> PersonList = new List<IPerson>(); private string meetingRoomMessage; public void AddPerson(IPerson person) { PersonList.Add(person); } public void NotifyPerson() { foreach(IPerson person in PersonList) { person.PrintMeetingRoomMessage(meetingRoomMessage); } } public void RemovePerson(IPerson person) { if(PersonList.Contains(person)) { PersonList.Remove(person); } } public void PublishMeetingRoomStatus(bool enabled) { string strStatus = "不可用"; if(enabled) { strStatus = "可用"; } meetingRoomMessage = $"当前会议室{strStatus}"; NotifyPerson(); } }
订阅者实现
public class PM : IPerson { private string PersonName { get; set; } private IMeetingRoom MeetingRoom { get; set; } public PM(string PMName, IMeetingRoom meetingRoom) { this.PersonName = PMName; this.MeetingRoom = meetingRoom; } public void PrintMeetingRoomMessage(string meetingRoomPublishMessage) { Console.WriteLine($"PM - {PersonName} : {meetingRoomPublishMessage}"); } public void SubscibeMeetingRoom() { MeetingRoom.AddPerson(this); } public void CancleSubscibeMeetingRoom() { MeetingRoom.RemovePerson(this); } }
public class Engineer : IPerson { private string PersonName { get; set; } private IMeetingRoom MeetingRoom { get; set; } public Engineer(string engineerName, IMeetingRoom meetingRoom) { this.PersonName = engineerName; this.MeetingRoom = meetingRoom; } public void PrintMeetingRoomMessage(string meetingRoomPublishMessage) { Console.WriteLine($"Engineer - {PersonName} : {meetingRoomPublishMessage}"); } public void SubscibeMeetingRoom() { MeetingRoom.AddPerson(this); } public void CancleSubscibeMeetingRoom() { MeetingRoom.RemovePerson(this); } }
代码测试
public static void Test() { MeetingRoom meetingRoom = new MeetingRoom(); IPerson person1 = new PM("张总", meetingRoom); IPerson person2 = new PM("李总", meetingRoom); IPerson person3 = new PM("李工", meetingRoom); IPerson person4 = new PM("张工", meetingRoom); person1.SubscibeMeetingRoom(); int num = 0; bool status = false; while (num < 6) { if (num % 2 == 0) { status = true; } else { status = false; } meetingRoom.PublishMeetingRoomStatus(status); num++; Console.WriteLine(num); if (num == 2) { person2.SubscibeMeetingRoom(); } if (num == 3) { person3.SubscibeMeetingRoom(); } if (num == 4) { person4.SubscibeMeetingRoom(); } } Console.ReadKey(); }
效果