抽象工厂是为了降低业务端和客户端的耦合度
1、消息接口
namespace IBLL { public interface IMsg { List<Model.Msg> GetMsgList(); } }
2、消息A实现
namespace BLLA.Abs { /// <summary> /// 抽象工厂调用 /// </summary> public class Msg:IBLL.IMsg { //DALFactory.AbsDALFactory DAL = DALFactory.AbsDALFactory.GetFactory(); public List<Model.Msg> GetMsgList() { //return DAL.GetDALMsg().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.AbsDALFactory DAL = DALFactory.AbsDALFactory.GetFactory(); //return DAL.GetDALMsg().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 abstract class AbsBLLFactory { public static AbsBLLFactory GetFactory() { string bll = ConfigurationManager.AppSettings["BLL"].ToString(); switch (bll) { case "BLLA": return new BLLFactory.BLLFactorA(); case "BLLB": return new BLLFactory.BLLFactorB(); } return null; } //public abstract IBLL.IUsers GetBllUser(); public abstract IBLL.IMsg GetBllMsg(); } }
5、抽象工厂A实现
namespace BLLFactory { /// <summary> /// 抽象工厂之实现 /// 1、业务逻辑A /// 继承抽象工厂类 /// 返回A业务逻辑的实现类 /// </summary> public class BLLFactorA : AbsBLLFactory { //public override IBLL.IUsers GetBllUser() //{ // return new BLLA.Abs.Users(); //} public override IBLL.IMsg GetBllMsg() { return new BLLB.Abs.Msg(); } } }
6、抽象工厂B实现
namespace BLLFactory { /// <summary> /// 抽象工厂之实现 /// 1、业务逻辑B /// 继承抽象工厂类 /// 返回B业务逻辑的实现类 /// </summary> public class BLLFactorB : AbsBLLFactory { //public override IBLL.IUsers GetBllUser() //{ // return new BLLA.Abs.Users(); //} public override IBLL.IMsg GetBllMsg() { return new BLLB.Abs.Msg(); } } }
7、客户端调用
客户端直接调用抽象工厂中的方法,不用去在客户端层体现具体实现代码方法,便于业务的切换
namespace Web { /// 和抽象工厂的区别: /// 1、抽象工厂在实现的时候,已经把不同业务的数据处理封装到简单工厂里。然后在通过抽象工厂针对简单工厂进行封装 /// 2、客户端调用的时候,可以new一个公共的实力, /// 3、如。可以“点”出用户实例 “点”出消息实例 public partial class AbsFactory : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //创建工厂公共对象 BLLFactory.AbsBLLFactory DAL = BLLFactory.AbsBLLFactory.GetFactory(); ////调用封装的用户接口信息 //List<Model.Users> listUsers = DAL.GetBllUser().GetUserList(); //foreach (Model.Users user in listUsers) //{ // Response.Write("UserId=[" + user.UserId + "]====UserName=[" + user.UserName + "]====AccountName=[" + user.AccountName + "]</br>"); //} //调用封装的消息信息 List<Model.Msg> listMsg = DAL.GetBllMsg().GetMsgList(); foreach (Model.Msg msg in listMsg) { Response.Write("MsgId=[" + msg.MsgId + "]</br>"); } } } }
抽象工厂简单示例