简单工厂模式的最大优点在于工厂类包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关类,对于客户端磊说,去除了与具体产品的依赖
对于简单工厂模式,其实就是将不同的东西抽象话,提取公共部分,然后以接口或者虚方法或者抽象成父类,然后针对不同的业务都继承,进而实现子类
这样就可以对外暴露一个父类即可,简单工厂进而将对外暴露的子类封装,可以通过参数传递,或者配置文件,亦或是反射进行工厂处理,进而达到对外暴露公共的目的,实现解耦的目的,便于业务的维护
案例说明
有两个消息需要发送(A和B),都继承于公共的消息接口,工厂返回的是公共的父类接口,但是内部是根据配置文件来判断实例化消息接口A还是消息接口B,
工厂实例化后,直接发送消息
1、消息产品接口

namespace IBLL { public interface IMsg { List<Model.Msg> GetMsgList(); } }
2、消息A实现

public class Msg:IBLL.IMsg { public List<Model.Msg> GetMsgList() { //DALFactory.SimpleDALFactory DAL = new DALFactory.SimpleDALFactory(); //return DAL.GetBLLMsg().GetMsgList(); List<Model.Msg> userList = new List<Model.Msg>() { new Model.Msg(){MsgId=Guid.NewGuid().ToString()}, new Model.Msg(){MsgId=Guid.NewGuid().ToString()} }; return userList; } }
3、消息B实现

public class Msg:IBLL.IMsg { public List<Model.Msg> GetMsgList() { //DALFactory.SimpleDALFactory DAL = new DALFactory.SimpleDALFactory(); //return DAL.GetBLLMsg().GetMsgList(); List<Model.Msg> userList = new List<Model.Msg>() { new Model.Msg(){MsgId=Guid.NewGuid().ToString()}, new Model.Msg(){MsgId=Guid.NewGuid().ToString()} }; return userList; } }
4、简单工厂类

namespace BLLFactory { /// <summary> /// 简单工厂 /// </summary> public class SimpleBLLFactory { //public IBLL.IUsers GetUserBLL() //{ // string bll = ConfigurationManager.AppSettings["BLL"].ToString(); // switch (bll) // { // case "BLLA": // return new BLLA.Simple.Users(); // case "BLLB": // return new BLLB.Simple.Users(); // } // return null; //} public IBLL.IMsg GetMsgBLL() { string bll = ConfigurationManager.AppSettings["BLL"].ToString(); switch (bll) { case "BLLA": return new BLLA.Simple.Msg(); case "BLLB": return new BLLB.Simple.Msg(); } return null; } } }
5、客户端调用

namespace Web { /// 和抽象工厂的区别: /// 1、简单工厂的不用业务类返回的时候,必须写单独的业务方法进行返回 /// 2、客户端调用的时候,必须定义不用的工厂实现方法 /// 3、如。new人员工厂实例 new消息工厂实例 public partial class SimpleFactory : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ////调用工厂接口 ////人员信息 //BLLFactory.SimpleBLLFactory DAL = new BLLFactory.SimpleBLLFactory(); //List<Model.Users> listUsers = DAL.GetUserBLL().GetUserList(); //foreach (Model.Users user in listUsers) //{ // Response.Write("UserId=[" + user.UserId + "]====UserName=[" + user.UserName + "]====AccountName=[" + user.AccountName + "]</br>"); //} /* *调用工厂接口 *消息信息 */ BLLFactory.SimpleBLLFactory Msg = new BLLFactory.SimpleBLLFactory(); List<Model.Msg> listMsg = Msg.GetMsgBLL().GetMsgList(); foreach (Model.Msg msg in listMsg) { Response.Write("MsgId=[" + msg.MsgId + "]</br>"); } } } }
具体项目结构
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步