上次写了基于MVC模式和Command模式构建系统架构,也做了一个简单的实例。
在把我想写的写完以后,我想通过一个具体的项目来串联大部分的设计模式思想。
今天我想说的是单件模式。
首先简单介绍下单件模式是什么东西,也称Singleton模式,实现单一实例的功能,不具体说了,不了解者看别的介绍概念性文章。
通常,在我做过的项目中,应用Singleton最多的就是做适配器,下面我会介绍如何做适配器。
先介绍通过通过单件模式,实现适配器产生单一实例的应用过程。
在介绍单件模式以前,我想先介绍下,面向服务编程的概念。在我现在的设计思想过程中,我认为,任何一个业务逻辑都是基于服务之上的。
服务是通过接口和实现来实现相互耦合。下面通过我之前开发的一个系统为例,抽象核心思想,来描述如何做适配器。
首先做个解决方案
做一个用户类服务接口
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
namespace IService
{
public interface IUserService
{
Users Load();
void Insert(User user);
void Update(User user);
void Delete(User user);
}
}
用户类实现
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IService;
using Model;
namespace Service
{
public class UserService:IUserService
{
#region IUserService 成员
public Model.Users Load()
{
Users returnUsers = new Users();
User myUser = new User();
myUser.Id = Guid.NewGuid().ToString();
myUser.Name = "zhangsan";
myUser.Password = "111";
User myUser1 = new User();
myUser1.Id = Guid.NewGuid().ToString();
myUser1.Name = "lisi";
myUser1.Password = "222";
returnUsers.Add(myUser);
returnUsers.Add(myUser1);
return returnUsers;
}
public void Insert(Model.User user)
{
throw new NotImplementedException();
}
public void Update(Model.User user)
{
throw new NotImplementedException();
}
public void Delete(Model.User user)
{
throw new NotImplementedException();
}
#endregion
}
}
业务实体
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class User
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class Users : List<User>
{
}
}
然后便是对于ServiceManager的建立了,这个类就是这个实例的核心类。
Code
// 适配管理器
static ServiceManager instance = null;
private static Object locker = new Object();
///
/// 单件模式应用,双层锁定
///
public static ServiceManager Instance
{
get
{
if (instance == null)
{
lock (locker)
{
if (instance == null)
{
instance = new ServiceManager();
}
}
}
return instance;
}
}
这里就是单件模式的应用,采用单件模式的作用就是通过适配器,加载不同服务的实现,产生唯一实例。
Code
///
/// 获取服务
///
/// 服务类型
///
///
public object GetService(Type serviceType)
{
if (ServiceTypes[serviceType.FullName] == null)
{
throw new Exception(serviceType.FullName + " 服务未找到!");
}
return ServiceTypes[serviceType.FullName];
}
///
/// 加载服务
///
public void Load()
{
if (this.ServiceTypes.Count > 0)
{
this.ServiceTypes.Clear();
}
lock (typeof(ServiceManager))
{
this.AllServiceAdd();
}
}
///
/// 所有服务加载
///
private void AllServiceAdd()
{
XmlDocument document = new XmlDocument();
Type type = null;
Type serviceType = null;
// boot.config启动文件
document.Load(@"D:\RayGu\Visual Studio 2008\WebSites\WebSite3\boot.config");
XmlElement documentElement = document.DocumentElement;
if (!((documentElement != null) && string.Equals(documentElement.Name, "Boot")))
{
throw new Exception(" boot.config服务配置失败!");
}
foreach (XmlNode node in documentElement.SelectNodes("/Boot/Services/Service"))
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement element2 = (XmlElement)node;
// 驱动
string attribute = element2.GetAttribute("Driver");
// 服务类型
string typeFullName = element2.GetAttribute("Type");
if (attribute == null)
{
throw new Exception(serviceType.FullName + " 服务驱动加载失败!");
}
type = ServiceManager.GetType(attribute);
serviceType = ServiceManager.GetType(typeFullName);
if (((type != null) && (serviceType != null)))
{
this.AcquireObject(type, serviceType.FullName);
}
else
{
throw new Exception(serviceType.FullName + " 服务加载失败!");
}
}
}
}
public object AcquireObject(Type type, string serviceTypeFullname)
{
if (this.ServiceTypes.Contains(serviceTypeFullname))
{
return this.ServiceTypes[serviceTypeFullname];
}
lock (this.ServiceTypes.SyncRoot)
{
this.ServiceTypes.Add(serviceTypeFullname, Activator.CreateInstance(type));
return this.ServiceTypes[serviceTypeFullname];
}
}
public static Type GetType(string typeFullName)
{
Type type = Type.GetType(typeFullName);
if (type != null)
{
return type;
}
string name = typeFullName.Substring(0, typeFullName.IndexOf(","));
string str2 = typeFullName.Substring(typeFullName.IndexOf(",") + 1);
string assemblyName = (str2.IndexOf(",") >= 0) ? str2.Substring(0, str2.IndexOf(",")) : str2;
name = name.Trim();
assemblyName = assemblyName.Trim();
if ((assemblyName != null) && (name != null))
{
Assembly assemblyByPartialName = GetAssemblyByPartialName(assemblyName);
if (assemblyByPartialName != null)
{
return assemblyByPartialName.GetType(name);
}
}
return null;
}
public static Assembly GetAssemblyByPartialName(string assemblyName)
{
string str = assemblyName + ",";
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.FullName.ToLower().StartsWith(str.ToLower()))
{
return assembly;
}
}
return null;
}
通过配置加载
xml version="1.0" encoding="utf-8" ?>
<Boot>
<Services>
<Service Type="IService.IUserService, IService" Driver="Service.UserService,
Service" />
Services>
Boot>
页面实现过程
Code
public static IUserService UserService
{
get
{
return (IUserService)ServiceManager.Instance.GetService(typeof(IUserService));
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Users users = UserService.Load();
string output = "";
output += "
编号 | 用户名 | 密码 |
";
foreach (User user in users)
{
output += "
" + user.Id + " |
" + user.Name + " |
" + user.Password + " |
";
}
output += "
";
this.PlaceHolder1.Controls.Add(new LiteralControl(output));
}
}
当然在实际开发过程中,通过多线程加载服务,控制多线程的单实例。