using System.Diagnostics.Metrics;
using System.Runtime.InteropServices;
using static 手写工厂模式.Program;namespace 手写工厂模式
{internal class Program{public interface eats {void eat();}//定义了一个接口public class rice : eats{public void eat() {Console.WriteLine("吃米饭");}}//继承接口并实现方法public class pig : eats{public void eat(){Console.WriteLine("吃猪猪");}}//继承接口并实现方法public class bird : eats{public void eat(){Console.WriteLine("吃小鸟");}}//继承接口并实现方法public class TransportFactory//创建一个工厂{public static eats GetTransport(string type)//eats 是指定的返回类型,表示该方法返回一个实现了 eats 接口的对象。{switch (type.ToLower()){case "rice":return new rice();case "pig":return new pig();case "bird":return new bird();default:throw new ArgumentException($"不支持该类型:{type}");//如果传入了没有的就会报错}}}static void Main(string[] args){eats transport = TransportFactory.GetTransport("rice");//这句是必须得它声明了transport的类型为eatstransport.eat();transport = TransportFactory.GetTransport("pig");//因为上面声明了transport的类型所以这里可以直接用transport.eat();}}}
输出