首页 > 代码库 > 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# 工厂模式示例