1. 简单工厂模式的介绍
简单工厂模式我们也可以理解为专门负责生产类的实例的类。
2. 简单工厂模式的用途
普通情况下创建类的实例需要使用new关键字,这样两个类之间就存在了依赖关系,如果对实例的类进行改造就需要同时修改依赖类,简单工厂模式将依赖关系从使用类中转移到工厂实现类中,当实现类变动时只需要修改工厂类的实现就可以,不会影响到依赖类
3. 简单工厂模式的思路
通过将类的实例创建过程封装到工厂类中
4.C# 实现代码
/// <summary>
/// 菜抽象类
/// </summary>
public abstract class Food
{
// 输出点了什么菜
public abstract void Print();
}
/// <summary>
/// 西红柿炒鸡蛋这道菜
/// </summary>
public class TomatoScrambledEggs : Food
{
public override void Print()
{
Console.WriteLine("一份西红柿炒蛋!");
}
}
/// <summary>
/// 土豆肉丝这道菜
/// </summary>
public class ShreddedPorkWithPotatoes : Food
{
public override void Print()
{
Console.WriteLine("一份土豆肉丝");
}
}
public class Customer
{
static void CreateFood()
{
// 客户想点一个西红柿炒蛋
Food food1 = SimpleFactory.CreateFood("西红柿炒蛋");
food1.Print();
// 客户想点一个土豆肉丝
Food food2 = SimpleFactory.CreateFood("土豆肉丝");
food2.Print();
Console.Read();
}
}
public class SimpleFactory
{
/// <summary>
/// 根据菜名创建具体的实例
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Food CreateFood(string type)
{
Food food = null;
if (type.Equals("土豆肉丝"))
{
food = new ShreddedPorkWithPotatoes();
}
else if (type.Equals("西红柿炒蛋"))
{
food = new TomatoScrambledEggs();
}
return food;
}
}
正文完