C# 工厂模式示例
Posted <抢囡囡糖未遂/>
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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# 工厂模式示例的主要内容,如果未能解决你的问题,请参考以下文章
设计模式简单工厂模式 ( 简介 | 适用场景 | 优缺点 | 代码示例 )