当前位置: 首页 > news >正文

.NET 设计模式—简单工厂(Simple Factory Pattern)

简介

简单工厂模式(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);
}

http://www.lryc.cn/news/334194.html

相关文章:

  • 聊聊Linux内核中内存模型
  • docker自动化部署示例
  • Redis精品案例解析:Redis实现持久化主要有两种方式
  • Python | Leetcode Python题解之第14题最长公共前缀
  • 烧坏两块单片机,不知道原因?
  • SV学习笔记(八)
  • Java反射常用方法
  • go语言实现无头单向链表
  • SpringBoot快速入门笔记(5)
  • solidity(3)
  • 笔记 | 编译原理L1
  • k8s存储卷 PV与PVC 理论学习
  • 【WPF应用32】WPF中的DataGrid控件详解与示例
  • numpy,matplotilib学习(菜鸟教程)
  • Web API(四)之日期对象节点操作js插件重绘和回流
  • 27.WEB渗透测试-数据传输与加解密(1)
  • 山寨windows
  • unity工程输出的log在哪里?
  • 【力扣】7. 整数反转
  • Android Apk签名算法使用SHA256
  • 2024.3.13力扣每日一题——最大二进制奇数
  • 2024.4.1力扣每日一题——故障键盘
  • 第十四届蓝桥杯C/C++大学B组题解(一)
  • 4.网络编程-websocket(golang)
  • docker安装部署mysql后忘记root密码
  • c++的学习之路:14、list(1)
  • huawei 华为交换机 配置 VLAN 聚合示例
  • 【QT+QGIS跨平台编译】056:【pdal-dimbuilder+Qt跨平台编译】(一套代码、一套框架,跨平台编译)
  • 【Python】探索Python中的aiohttp:构建高效并发爬虫
  • 创建真实项目vue2项目