1.作业内容
使用 C# 编码(涉及类、接口、委托等关键知识点),实现对周黑鸭工厂的产品生产统一管理,主要产品包括鸭脖和鸭翅。武汉工厂能生生产鸭脖和鸭翅,南京工厂只能生产鸭翅,长沙工厂只能生产鸭脖。
具体要求如下:
定义接口 IProductionFactory,包含生产鸭脖和鸭翅的方法。
定义类WuhanFactory、NanjingFactory、ChangshaFactory 分别实现接口 IProductionFactory,用于具体的生产工厂。
使用委托 ProductionDelegate 定义生产委托。
在 Main 函数中,创建不同工厂的实例,并通过生产委托进行生产。
作业要求
- 请以博客方式提交作业,博客内容需要对代码行进行讲解,阐述设计的主要思路与难点。请注意,如果想达到博客网站如csdn的优质博文的质量分,需要对博客进行详细描述。
- 提交方式为提交博客发布地址,并附上本博文的质量分。
2.主要思路
(1)接口
定义接口:
interface IProductionFactory
{
void ProduceDuckNeck();
void ProduceDuckWing();
}
(2)类实现接口
class WuhanFactory : IProductionFactory
{
public void ProduceDuckNeck()
{
Console.WriteLine("武汉生产鸭脖");
}
public void ProduceDuckWing()
{
Console.WriteLine("武汉生产鸭翅");
}
}
(3)声明委托
// 定义生产委托
delegate void ProductionDelegate();
(4)实例化
在Main
函数中,首先创建了WuhanFactory
、NanjingFactory
和ChangshaFactory
的实例,分别赋值给wuhanFactory
、nanjingFactory
和changshaFactory
变量
IProductionFactory wh = new WuhanFactory();
IProductionFactory nj = new NanjingFactory();
IProductionFactory cs = new ChangshaFactory();
(5)实例化委托
ProductionDelegate productionDelegate = wh.ProduceDuckNeck;
productionDelegate += wh.ProduceDuckWing;
productionDelegate += nj.ProduceDuckWing;
productionDelegate += cs.ProduceDuckNeck;
3.代码实现
using System;
// 定义生产委托
delegate void ProductionDelegate();
// 定义生产工厂接口
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("长沙不能生产鸭翅");
}
}
class Program
{
static void Main(string[] args)
{
IProductionFactory wh = new WuhanFactory();
IProductionFactory nj = new NanjingFactory();
IProductionFactory cs = new ChangshaFactory();
ProductionDelegate productionDelegate = wh.ProduceDuckNeck;
productionDelegate += wh.ProduceDuckWing;
productionDelegate += nj.ProduceDuckWing;
productionDelegate += cs.ProduceDuckNeck;
productionDelegate.Invoke();
Console.ReadLine();
}
}