目录
前言
使用 C# 编码(涉及类、接口、委托等关键知识点),实现对周黑鸭工厂的产品生产统一管理,主要产品包括鸭脖和鸭翅。武汉工厂能生生产鸭脖和鸭翅,南京工厂只能生产鸭翅,长沙工厂只能生产鸭脖。
一、设计思路
首先定义接口IProductionFactory,包含生产鸭脖(ProduceDuckneck)和鸭翅(ProduceDuckwing)的方法。再定义类 WuhanFactory、NanjingFactory、ChangshaFactory 分别实现接口 IProductionFactory,用于具体的生产工厂。然后使用委托 ProductionDelegate 定义生产委托。最后在 Main 函数中,创建不同工厂的实例,并通过生产委托进行生产。
二、代码实现
1.定义接口
public interface IProductionFactory
{
void ProduceDuckneck();
void ProduceDuckwing();
}
2.定义工厂类
class WuhanFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("武汉工厂生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("武汉工厂生产鸭翅");
}
}
class NanjingFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("南京工厂不能生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("南京工厂生产鸭翅");
}
}
class ChangshaFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("长沙工厂生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("长沙工厂不能生产鸭翅");
}
}
3.定义委托
public delegate void ProductionDelegate();
4.主函数
class Production
{
static void Main(string[] args)
{
WuhanFactory wuhanFactory = new WuhanFactory();
NanjingFactory nanjingFactory = new NanjingFactory();
ChangshaFactory changshaFactory = new ChangshaFactory();
ProductionDelegate duckneckproduce = new ProductionDelegate(wuhanFactory.ProduceDuckneck);
duckneckproduce += changshaFactory.ProduceDuckneck;
ProductionDelegate duckwingproduce = new ProductionDelegate(wuhanFactory.ProduceDuckwing);
duckwingproduce += nanjingFactory.ProduceDuckwing;
Console.WriteLine("生产鸭脖");
duckneckproduce();
Console.WriteLine("生产鸭翅");
duckwingproduce();
}
}
三、总结
1.完整代码
//定义接口
public interface IProductionFactory
{
void ProduceDuckneck();
void ProduceDuckwing();
}
//定义类
class WuhanFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("武汉工厂生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("武汉工厂生产鸭翅");
}
}
class NanjingFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("南京工厂不能生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("南京工厂生产鸭翅");
}
}
class ChangshaFactory : IProductionFactory
{
public void ProduceDuckneck()
{
Console.WriteLine("长沙工厂生产鸭脖");
}
public void ProduceDuckwing()
{
Console.WriteLine("长沙工厂不能生产鸭翅");
}
}
//定义委托
public delegate void ProductionDelegate();
//主函数
class Production
{
static void Main(string[] args)
{
WuhanFactory wuhanFactory = new WuhanFactory();
NanjingFactory nanjingFactory = new NanjingFactory();
ChangshaFactory changshaFactory = new ChangshaFactory();
ProductionDelegate duckneckproduce = new ProductionDelegate(wuhanFactory.ProduceDuckneck);
duckneckproduce += changshaFactory.ProduceDuckneck;
ProductionDelegate duckwingproduce = new ProductionDelegate(wuhanFactory.ProduceDuckwing);
duckwingproduce += nanjingFactory.ProduceDuckwing;
Console.WriteLine("生产鸭脖");
duckneckproduce();
Console.WriteLine("生产鸭翅");
duckwingproduce();
}
}