using System;
// 定义接口 IProductionFactory
public interface IProductionFactory
{
void ProduceDuckNeck();
void ProduceDuckWing();
}
// 定义武汉工厂类,实现 IProductionFactory 接口
public class WuhanFactory : IProductionFactory
{
public void ProduceDuckNeck()
{
Console.WriteLine("武汉工厂生产鸭脖");
}
public void ProduceDuckWing()
{
Console.WriteLine("武汉工厂生产鸭翅");
}
}
// 定义南京工厂类,实现 IProductionFactory 接口
public class NanjingFactory : IProductionFactory
{
public void ProduceDuckNeck()
{
throw new NotImplementedException("南京工厂不能生产鸭脖");
}
public void ProduceDuckWing()
{
Console.WriteLine("南京工厂生产鸭翅");
}
}
// 定义长沙工厂类,实现 IProductionFactory 接口
public class ChangshaFactory : IProductionFactory
{
public void ProduceDuckNeck()
{
Console.WriteLine("长沙工厂生产鸭脖");
}
public void ProduceDuckWing()
{
throw new NotImplementedException("长沙工厂不能生产鸭翅");
}
}
// 定义生产委托
public delegate void ProductionDelegate();
class Program
{
static void Main(string[] args)
{
// 创建工厂实例
IProductionFactory wuhanFactory = new WuhanFactory();
IProductionFactory nanjingFactory = new NanjingFactory();
IProductionFactory changshaFactory = new ChangshaFactory();
// 创建生产委托实例
ProductionDelegate produceDuckNeckDelegate = wuhanFactory.ProduceDuckNeck;
ProductionDelegate produceDuckWingDelegate = nanjingFactory.ProduceDuckWing;
// 通过生产委托进行生产
produceDuckNeckDelegate();
produceDuckWingDelegate();
// 另一种使用方式,直接调用工厂方法
changshaFactory.ProduceDuckNeck();
// 尝试使用不支持的生产方法会抛出异常
// changshaFactory.ProduceDuckWing(); // 这行代码会抛出 NotImplementedException
}
}
使用 C# 编码(涉及类、接口、委托等关键知识点),实现对周黑鸭工厂的产品生产统一管理,主要产品包括鸭脖和鸭翅。
最新推荐文章于 2024-08-14 21:15:00 发布