gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
采用委托,实现发布-订阅机制。模拟实现邮局-用户例子。即用户订阅报刊,邮局发布通知,用户通过自定义方式取报刊。写出代码及运行结果。
- User
采用委托,实现发布-订阅机制。模拟实现邮局-用户例子。即用户订阅报刊,邮局发布通知,用户通过自定义方式取报刊。写出代码及运行结果。
- Assistant
下面是使用委托实现发布-订阅机制的代码:
using System; using System.Collections.Generic; // 定义报刊类 public class Newspaper { public string Title { get; set; } public Newspaper(string title) { Title = title; } } // 定义订阅者类 public class Subscriber { public string Name { get; set; } public Subscriber(string name) { Name = name; } // 定义接收通知的方法 public void ReceiveNotification(Newspaper newspaper) { Console.WriteLine("{0} received the newspaper: {1}", Name, newspaper.Title); } } // 定义邮局类 public class PostOffice { // 声明委托类型 public delegate void NotificationHandler(Newspaper newspaper); // 定义委托实例 public NotificationHandler OnNewspaperPublished; // 发布通知的方法 public void PublishNewspaper(Newspaper newspaper) { OnNewspaperPublished?.Invoke(newspaper); } } public class Program { public static void Main(string[] args) { // 创建邮局和订阅者对象 PostOffice postOffice = new PostOffice(); Subscriber subscriber1 = new Subscriber("Alice"); Subscriber subscriber2 = new Subscriber("Bob"); // 订阅报刊 postOffice.OnNewspaperPublished += subscriber1.ReceiveNotification; postOffice.OnNewspaperPublished += subscriber2.ReceiveNotification; // 发布通知 Newspaper newspaper = new Newspaper("Daily News"); postOffice.PublishNewspaper(newspaper); } } - User
定义一个设备(IDevice)接口,该接口描述设备的启动(start),停止(stop),维修(maintain),工作(run)等功能。 在接口之上,定义派生类-抽象类Device,该类包含设备编号,名称,使用者名字,使用日期等信息。 在抽象类Device上派生出手机类Mobile,实现启动,停止,维修,工作等功能。编写代码测试手机类的功能。写出代码及运行结果。
- Assistant
下面是设备接口和手机类的代码:
using System; // 设备接口 public interface IDevice { void Start(); void Stop(); void Maintain(); void Run(); } // 抽象类设备 public abstract class Device : IDevice { public string DeviceId { get; set; } public string DeviceName { get; set; } public string UserName { get; set; } public DateTime UseDate { get; set; } public Device(string deviceId, string deviceName) { DeviceId = deviceId; DeviceName = deviceName; UseDate = DateTime.Now; } public abstract void Start(); public abstract void Stop(); public abstract void Maintain(); public abstract void Run(); } // 手机类 public class Mobile : Device { public Mobile(string deviceId, string deviceName) : base(deviceId, deviceName) { } public override void Start() { Console.WriteLine("Mobile {0} started", DeviceId); } public override void Stop() { Console.WriteLine("Mobile {0} stopped", DeviceId); } public override void Maintain() { Console.WriteLine("Mobile {0} is under maintenance", DeviceId); } public override void Run() { Console.WriteLine("Mobile {0} is running", DeviceId); } } // 测试手机类的功能 public class Program { public static void Main(string[] args) { Mobile mobile = new Mobile("123456789", "iPhone"); mobile.Start(); mobile.Run(); mobile.Stop(); mobile.Maintain(); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.