单例模式:DbContextFactory.cs
using CZBK.ItcastOA.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks; namespace CZBK.ItcastOA.DAL
{
public class DbContextFactory
{
/// <summary>
/// 保证EF上下文实例线程内唯一.
/// </summary>
/// <returns></returns>
public static DbContext CreateDbContext()
{
DbContext dbContext = (DbContext)CallContext.GetData("db");
if (dbContext == null)
{
dbContext = new OAEntities();
CallContext.SetData("db", dbContext);
}
return dbContext;
}
}
}
public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
工厂模式:SimpleFactory.cs
using CZBK.Shop.IDal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CZBK.Shop.DalFactory
{
/// <summary>
/// 工厂模式:解决的就是对象的创建(将对象的创建封装起来)
/// </summary>
public class SimpleFactory
{
public static IUserInfoDal CreateUserInfoDal()
{
return new SqlServerDal.UserInfoDal();
}
}
}
抽象工厂模式:AbstractFactory.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace CZBK.Shop.DalFactory
{
/// <summary>
/// 抽象工厂:本质上与工厂是一样的,都是负责创建对象,但是创建的方式不一样。
/// </summary>
public class AbstractFactory
{
private static readonly string DalAssembly = ConfigurationManager.AppSettings["DalAssembly"];
private static readonly string DalNameSpace = ConfigurationManager.AppSettings["DalNameSpace"];
public static IDal.IUserInfoDal CreateUserInfoDal()
{
//通过反射的形式来创建.
string fullClassName = DalNameSpace + ".UserInfoDal";
return CreateInstance(fullClassName) as IDal.IUserInfoDal;
}
private static object CreateInstance(string fullClassName)
{
var assmebly = Assembly.Load(DalAssembly);//加载程序集.
return assmebly.CreateInstance(fullClassName);
}
}
}