单例模式应用
再一个类库中创建一个Factory,这个Factory用于调用其他类,从而调用其他类中的方法
DALFactory中:
public class DALFactory {
private static DALFactory _instance;
//单例模式 public static DALFactory Instance
{
get
{
if(_instance==null)
{
_instance=new DALFactory();
}
return _instance;
}
} private DALFactory() { } public UsersDAL UsersDAL { get { return new UsersDAL(); } } }
普通类:
public class UsersDAL { //public static UsersDAL Instance { get { return new UsersDAL(); } } //private UsersDAL() { } #region 用户登录 /// <summary> /// 用户登录 /// </summary> /// <param name="username">用户名</param> /// <param name="password">用户密码</param> /// <returns>该用户</returns> public Users UserLogin(string username, string password) { Users user = null; using (EF.schoolshopEntities content = new EF.schoolshopEntities()) { var entity = content.SS_Users.FirstOrDefault(u => u.UserName == username && u.Password == password &&u.DelFlag==0); if (entity != null) { user = CreatUser(user, entity); } } return user; } /// <summary> /// 根据uid获取用户 /// </summary> /// <param name="uid">用户ID</param> /// <returns>该用户</returns> public Users GetUserByUID(int uid) { Users user = null; using (EF.schoolshopEntities content = new EF.schoolshopEntities()) { var entity = content.SS_Users.FirstOrDefault(u => u.UID == uid); if (entity != null) { user = CreatUser(user, entity); } } return user; } /// <summary> /// 实体转化成模型 /// </summary> /// <param name="user"></param> /// <param name="entity"></param> /// <returns></returns> private Users CreatUser(Users user, EF.SS_Users entity) { user = new Users() { UID = entity.UID, UserName = entity.UserName, Password = entity.Password, NickName = entity.NickName, Mobile = entity.Mobile, Email = entity.Email, Gender = entity.Gender, Address = entity.Address, LastLoginTime = entity.LastLoginTime, Birthday = entity.Birthday, RegistTime = entity.RegistTime, }; return user; } #endregion }
BLLFactory中:
public class BLLFactory { public static BLLFactory Instance { get { return new BLLFactory(); } } private BLLFactory() { } public UsersBLL UsersBLL { get { return new UsersBLL(); } } }
普通类:
public class UsersBLL { //public static UsersBLL Instance { get { return new UsersBLL(); } } //private UsersBLL() { } #region 用户登录 /// <summary> /// 判断用户登录 /// </summary> /// <param name="username">用户名</param> /// <param name="password">用户密码</param> /// <returns>该用户</returns> public Users UserLogin(string username, string password) { Users user = DALFactory.Instance.UsersDAL.UserLogin(username, password); //UsersDAL.Instance.UserLogin(username, password); return user; } /// <summary> /// 根据uid获取用户 /// </summary> /// <param name="uid">用户ID</param> /// <returns>该用户</returns> public Users GetUserByUID(int uid) { Users user = DALFactory.Instance.UsersDAL.GetUserByUID(uid); //UsersDAL.Instance.GetUserByUID(uid); return user; } #endregion }
如果点的太多可以:
private UsersDAL _userDao; public UsersBLL() { _userDao = DALFactory.Instance.UsersDAL; }