简介
简单工厂模式(Simple Factory Pattern)属于类的创建型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过一个工厂类来创建对象,根据不同的参数或条件返回相应的对象实例。这种模式隐藏了对象的创建细节,客户端只需通过工厂类获取对象而不需要直接实例化对象。
优点
- 只需要传入 正确的参数 , 就可以 获取需要的对象 , 无需知道创建细节 ;
- 工厂类中有必要的 判断逻辑 , 可以决定 根据当前的参数 创建对应的产品实例 , 客户端可以免除直接创建产品对象的责任 ;
- 通过该模式 , 实现了对 创建实例 和 使用实例 的 责任分割 ;
- 提供专门的 工厂类 用于创建对象 , 客户端 无需知道所创建的产品类的类名 , 只需要知道对应产品类的参数即可创建对象实例 ;
缺点
- 工厂类 职责 过重 , 如果要增加新的产品 , 需要 修改工厂类的判断逻辑 , 违背 " 开闭原则 " ;
- 7 大设计原则 , 不能全部遵守 , 也不能不遵守 , 注意平衡 功能 和 系统复杂度 , 找到最合适的一个点 ;
应用场景
-
创建对象少 : 工厂类 负责 创建的对象 比较少 ;
-
不关心创建过程 : 客户端 只知道 传入 工厂类 的参数 , 对于 如何创建对象 不关心 ;
实现
- 创建一个学生的接口类:IStudent
public interface IStudent
{
public void Study();
}
- 创建三个子类:SmallStudent、MiddleStudent、LargeStudent继承接口IStuent
public class SmallStudent : IStudent
{
public void Study()
{
Console.WriteLine("小学生在学习");
}
}
public class MiddleStudent : IStudent
{
public void Study()
{
Console.WriteLine("中学生在学习!");
}
}
public class LargeStudent : IStudent
{
public void Study()
{
Console.WriteLine("大学生在学习");
}
}
- 创建单独的简单工厂类统一创建实例
public class SimpleFactory
{
/// <summary>
/// 简单工厂
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public static IStudent CreateInstance(StudentType type)
{
IStudent student = null;
switch (type)
{
case StudentType.SmallStudent:
student = new SmallStudent();
break;
case StudentType.MiddleStudent:
student = new MiddleStudent();
break;
case StudentType.LargeStudent:
student = new LargeStudent();
break;
default:
throw new NotImplementedException();
}
return student;
}
}
public enum StudentType : int
{
[Description("小学生")]
SmallStudent = 0,
[Description("中学生")]
MiddleStudent = 1,
[Description("大学生")]
LargeStudent = 2,
}
- 演示上层调用
{
IStudent smallStudent = SimpleFactory.CreateInstance(StudentType.SmallStudent);
IStudent middleStudent = SimpleFactory.CreateInstance(StudentType.MiddleStudent);
IStudent largeStudent = SimpleFactory.CreateInstance(StudentType.LargeStudent);
}