首页 > 代码库 > C# 工厂模式示例
C# 工厂模式示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 工厂模式 { class Program { static void Main(string[] args) { //初始化做菜的工厂 Creator shreddedPorkWithPotatoesFactory = new ShreddedPorkWithPotatoesFactory(); Creator tomatoScrambledEggsFactory = new TomatoScrambledEggsFactory(); //生产西红柿炒蛋 Food tomatoScrambleEggs = tomatoScrambledEggsFactory.CreateFoodFactory(); tomatoScrambleEggs.Print(); //生产土豆肉丝 Food shreddedPorkWithPotatoes = shreddedPorkWithPotatoesFactory.CreateFoodFactory(); shreddedPorkWithPotatoes.Print(); Console.ReadKey(); } } /// <summary> /// 菜抽象类 /// </summary> public abstract class Food { /// <summary> /// 抽象方法输出什么菜 /// </summary> public abstract void Print(); } /// <summary> /// 做西红柿炒蛋 /// </summary> public class TomatoScrambledEggs : Food { /// <summary> /// 重载Food的抽象方法Print /// </summary> public override void Print() { Console.WriteLine("西红柿炒蛋已经准备完毕!"); } } /// <summary> /// 做土豆肉丝 /// </summary> public class ShreddedPorkWithPotatoes : Food { /// <summary> /// 重载Food的抽象方法Print /// </summary> public override void Print() { Console.WriteLine("土豆肉丝已经准备完毕!"); } } /// <summary> /// 抽象工厂类 /// </summary> public abstract class Creator { public abstract Food CreateFoodFactory(); } /// <summary> /// 西红柿炒蛋工厂 /// </summary> public class TomatoScrambledEggsFactory : Creator { /// <summary> /// 重载创建西红柿这个菜 /// </summary> /// <returns></returns> public override Food CreateFoodFactory() { return new TomatoScrambledEggs(); } } /// <summary> /// 土豆肉丝工厂 /// </summary> public class ShreddedPorkWithPotatoesFactory:Creator { /// <summary> /// 创建土豆肉丝这个菜 /// </summary> /// <returns></returns> public override Food CreateFoodFactory() { return new ShreddedPorkWithPotatoes(); } } }
C# 工厂模式示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。