简单工厂模式

原理



BLL层

BLL类库

BaseBll.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{

    //BLL层只实现IBLL层的接口,不直接与DAL层打交道
    using IBLL;
    using IDAL;
    public class BaseBll<T> : IBaseBllInterface<T> where T:class //父类方法只实现父类接口
    {
        protected IBaseDalInterface<T> basedal;
        public List<T> QueryWhere(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return basedal.QueryWhere(where);
        }

        public bool DeleteWhere(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return basedal.DeleteWhere(where);
        }
    }
}
T_UserInfoBll.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    using IBLL;
    using IDAL;
    using Model;
    using DALFactroy;

    //这里为什么要继承这个借口呢?那是因为虽然T_UserInfoBll继承了 BaseBll<T_UserInfo>类,而且 BaseBll<T_UserInfo>类也实现了IBaseBll<T>接口口。但是IT_UserInfoBllInterface是继承自IBaseBll<T>接口的,在IT_UserInfoBllInterface接口中可以有存在它自己的独特方法。如果你想用IT_UserInfoBllInterface接口中的独特方法的话,那么就就需要来继承这个IT_UserInfoBllInterface接口并实现它。 (子类实现对应的子类接口)
    public class T_UserInfoBll : BaseBll<T_UserInfo>, IT_UserInfoBllInterface 
    {
        IT_UserInfoDalInterface dal;
        public T_UserInfoBll()
        {
            this.dal = DalFactroy.CreateUserInfoDalInstance(); //创建子类dal对象(如果子接口中有方法,这个子类需要实现)
            base.basedal = this.dal; 
        }

    }
}

IBLL类库

IBaseBllInterface.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IBLL
{
    /// <summary>
    /// 定义方法在这里,BLL层只要实现这个接口中的方法就可以了,其他都不用管(不管更换什么BLL,新来的BLL只需要实现IBLL中的方法)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IBaseBllInterface<T> where T:class
    {
        List<T> QueryWhere(System.Linq.Expressions.Expression<Func<T, bool>> where);

        bool DeleteWhere(System.Linq.Expressions.Expression<Func<T, bool>> where);
    }
}

IT_UserInfoBllInterface.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IBLL
{
    using IBLL;
    using Model;

   
    public interface IT_UserInfoBllInterface:IBaseBllInterface<T_UserInfo>
    {
        //这里除了继承IBaseBllInterface<T_UserInfo>接口中的方法外,还可以定义自己的抽象方法,继承它的子类需要实现
    }
}


BLLFactroy类库

BllFactroy.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BLLFactroy
{
    using IBLL;

    /// <summary>
    /// 这个BLL层的工厂是给UI层来调用的(目的是创建BLL层的对象)
    /// </summary>
    public class BllFactroy
    {
        static object CreateObject(string className)
        {
            string assName = System.Configuration.ConfigurationManager.AppSettings["bll"];
            if (string.IsNullOrEmpty(assName))
            {
                throw new Exception("没配置BLL程序集的名称");
            }

            Assembly ass = Assembly.Load(assName);
            //如果对象创建不成功,查询下UI层中使用EF的版本是不是与类库中引用的EF版本不一致。
            return ass.CreateInstance(assName + "." + className);

        }

        /// <summary>
        /// 创建T_UserInfoBll类对象
        /// </summary>
        /// <returns>将T_UserInfoBll类对象以IT_UserInfoBllInterface接口的形式返回</returns>
        public static IT_UserInfoBllInterface  CreateUserInfoInstance()
        {
            return CreateObject("T_UserInfoBll") as IT_UserInfoBllInterface;
        }
    }
}

DAL层

DAL类库

BaseDal.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    using IDAL;
    using DALFactroy;
    public class BaseDal<T>:IBaseDalInterface<T> where T:class
    {
        //BaseDbContext db = new BaseDbContext();

        //上下文类我们也可以通过反射来创建上下文类对象(因为这个BaseDbContext上下文类就在DAL层中,那我们通过反射DAL.dll程序集就可以得到它的对象)
        BaseDbContext db = DalFactroy.CreateBaseDbContextDalInstance() as BaseDbContext;
        public List<T> QueryWhere(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
           return  db.Set<T>().Where(where).ToList();
            
        }

        //根据条件批量删除
        public bool DeleteWhere(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            List<T> list = db.Set<T>().Where(where).ToList();
            try
            {
                list.ForEach(r => db.Set<T>().Remove(r));
                db.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            
        }
    }
}
BaseDbContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    using IDAL;
    public class BaseDbContext : DbContext, IBaseDbContextDalInterface //这里我让它多继承了一个接口,用于通过反射,将BaseDbContext对象以IBaseDbContextDalInterface接口的形式返回。
    {
        public BaseDbContext()
            : base("name=salesEntities")
        {
            base.Database.CreateIfNotExists();  
        }
    }
}
T_UserInfoDal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    using Model;
    using IDAL;
    public class T_UserInfoDal:BaseDal<T_UserInfo>,IT_UserInfoDalInterface
    {

    }
}<span style="color:#3366ff;">
</span>

IDAL类库

IBaseDalInterface.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace IDAL
{
    public interface IBaseDalInterface<T> where T:class
    {
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
         List<T> QueryWhere(Expression<Func<T, bool>> where);
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        bool DeleteWhere(Expression<Func<T, bool>> where);
    }
}
IBaseDbContextDalInterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDAL
{
    public interface IBaseDbContextDalInterface
    {
        //这里不需要其他的方法,仅仅是定义了一个接口在这里。这么做的原因其实就是因为DAL层只会引用IDAL层和DALFactroy层。
        //那么我们在DALFactroy层工厂中创建的BaseDbContext上下文类对象就只能以接口的形式返回,所以需要有这么一个接口供他放回对象
        //如果在DALFactroy工厂中创建的BaseDbContext上下文类对象直接以BaseDbContext类的形式放回,那么这个BaseDbContext类存在与DAL层中,
        //而原则上DALFactroy是不与DAL层打交道的。DALFactroy只与IDAL打交道(DALFactroy只引用IDAL 即using IDAL)
        //所以这里我们才将BaseDbContext上下文类对象以接口的形式返回
    }
}
IT_UserInfoDalInterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDAL
{
    using Model;
    public interface IT_UserInfoDalInterface:IBaseDalInterface<T_UserInfo>
    {
        //这里也可以定义IT_UserInfoDalInterface接口中的特有方法。
    }
}


DALFactroy类库

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DALFactroy
{
    using IDAL;

    /// <summary>
    /// 这个Dal层的工厂是给BLL层的类调用的
    /// </summary>
    public class DalFactroy
    {
        static object CreateObject(string className)
        {
            string assName = System.Configuration.ConfigurationManager.AppSettings["dal"];
            if (string.IsNullOrEmpty(assName))
            {
                throw new Exception("没有配置dal程序集名称");
            }
            else
            {
                Assembly ass = Assembly.Load(assName);
                Type t = ass.GetType(assName + ".T_UserInfoDal");
                if (t == null)
                    throw new Exception(assName + "程序集中不存在" + className + "类");

                //如果对象创建不成功,查询下UI层中使用的EF的版本是不是与类库中引用的EF版本不一致。
                return ass.CreateInstance(assName + "." + className);
            }

        }
       
        /// <summary>
        /// 创建T_UserInfoDal类的对象
        /// </summary>
        /// <returns>将这个T_UserInfoDal类的对象以IT_UserInfoDalInterface接口的形式返回</returns>
        public static IT_UserInfoDalInterface CreateUserInfoDalInstance()
        {
            return CreateObject("T_UserInfoDal") as IT_UserInfoDalInterface;
        }
        /// <summary>
        /// 创建BaseDbContext类对象
        /// </summary>
        /// <returns>将这个BaseDbContext类对象以IBaseDbContextDalInterface接口的形式返回</returns>
        public static IBaseDbContextDalInterface CreateBaseDbContextDalInstance()
        {
            return CreateObject("BaseDbContext") as IBaseDbContextDalInterface;
        }

    }
}

UI层

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApp.Controllers
{
    using BLLFactroy;
    public class HomeController : Controller
    {
            
        public ActionResult Index()
        {
            //调用业务层中的工厂,创建BLL层中的类的对象。
            var s = BllFactroy.CreateUserInfoInstance().QueryWhere(r => r.Age > 10);
            return View();
        }
	}
}

web.config (部分内容)

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcApp-20160426030737.mdf;Initial Catalog=aspnet-MvcApp-20160426030737;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    
    <!--EF连接数据库的连接字符串-->
    <add name="salesEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=F........;initial catalog=sales;persist security info=True;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <!--配置用于反射某个程序集的名称-->
    <add key="bll" value="BLL"/>
    <add key="dal" value="DAL"/>
  </appSettings>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值