首页 > 代码库 > 003-单例OR工厂模式

003-单例OR工厂模式

单例模式:DbContextFactory.cs

 1 using CZBK.ItcastOA.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.Entity;
 5 using System.Linq;
 6 using System.Runtime.Remoting.Messaging;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace CZBK.ItcastOA.DAL
11 {
12     public class DbContextFactory
13     {
14         /// <summary>
15         /// 保证EF上下文实例线程内唯一.
16         /// </summary>
17         /// <returns></returns>
18         public static DbContext CreateDbContext()
19         {
20             DbContext dbContext = (DbContext)CallContext.GetData("db");
21             if (dbContext == null)
22             {
23                 dbContext = new OAEntities();
24                 CallContext.SetData("db", dbContext);
25             }
26             return dbContext;
27         }
28     }
29 }

工厂模式:SimpleFactory.cs

 1 using CZBK.Shop.IDal;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace CZBK.Shop.DalFactory
 9 {
10     /// <summary>
11     /// 工厂模式:解决的就是对象的创建(将对象的创建封装起来)
12     /// </summary>
13     public class SimpleFactory
14     {
15         public static IUserInfoDal CreateUserInfoDal()
16         {
17             return new SqlServerDal.UserInfoDal();
18         }
19     }
20 }

抽象工厂模式:AbstractFactory.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Configuration;
 4 using System.Linq;
 5 using System.Reflection;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace CZBK.Shop.DalFactory
10 {
11     /// <summary>
12     /// 抽象工厂:本质上与工厂是一样的,都是负责创建对象,但是创建的方式不一样。
13     /// </summary>
14     public class AbstractFactory
15     {
16         private static readonly string DalAssembly = ConfigurationManager.AppSettings["DalAssembly"];
17         private static readonly string DalNameSpace = ConfigurationManager.AppSettings["DalNameSpace"];
18         public static IDal.IUserInfoDal CreateUserInfoDal()
19         {
20             //通过反射的形式来创建.
21             string fullClassName = DalNameSpace + ".UserInfoDal";
22             return CreateInstance(fullClassName) as IDal.IUserInfoDal;
23         }
24         private static object CreateInstance(string fullClassName)
25         {
26             var assmebly = Assembly.Load(DalAssembly);//加载程序集.
27             return assmebly.CreateInstance(fullClassName);
28         }
29     }
30 }

 

003-单例OR工厂模式