在实际的开发过程中,我们会遇到这样的一种情况:例如我的调用类有一个方法,但是这个方法却需要去调用的类的方法进行处理。有点晕了哈,好吧 我们一边看代码一边说问题。
首先我们上底层方法:
public class DelegateMyFunction
{
public static string NowTime = string.Empty;
private static DelegateMyFunction instance = null;
private static readonly object padlock = new object();
public static DelegateMyFunction Instance(UpdateDataTime updateTime)
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new DelegateMyFunction(updateTime);
}
}
}
return instance;
}
public DelegateMyFunction(UpdateDataTime updateTime)
{
ParameterizedThreadStart ParStart = new ParameterizedThreadStart(WhileUpdate);
Thread myThread = new Thread(ParStart);
object o = updateTime;
myThread.Start(o);
}
public void WhileUpdate(object updateTime)
{
while (true)
{
DateTime datetime = ((UpdateDataTime)updateTime)();
NowTime = datetime.ToString("HH时mm分钟ss秒");
Thread.Sleep(5000);
}
}
public delegate DateTime UpdateDataTime();
}
这个是我的一个底层类,但是底层类里面 我需要一个更新的方法,但是更新的方法却不是我定的,需要调用类去定,因为不同的调用类需要方法是不定的,但是我又不想在这个类里卖弄把所有的方法写在里面。因为,这样非常影响我的可扩展性。同时我这个是个基类,如果过多的涉及业务的范畴,它职能就太多,也让我们的架构变得模糊不清。但是为了保证这个类只能被实例化一次(因为我们在实例化的时候使用了线程,如果实例化多次,会造成后台多个线程在运作),我需要需要给类使用单例模式,为了让外部方法能把处理的方法使用参数的方式进行传参,我们需要使用委托。
private static DelegateMyFunction instance = null;
private static readonly object padlock = new object();
public static DelegateMyFunction Instance(UpdateDataTime updateTime)
三个地方是我们的锁。
public DelegateMyFunction(UpdateDataTime updateTime) 要我们实例化,必须带参数,参数是我们的委托。public delegate DateTime UpdateDataTime();
同时在实例化类以后,我们就使用线程调用我们的 public void WhileUpdate(object updateTime)方法,而WhileUpdate的主要作用就是 调用我们的外部方法,然后间隔5秒再去进行调用。达到定时更新的作用。
下面是我们调用类:
public partial class DelegatePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["type"] == null)
{
DelegateMyFunction FunctionTest = DelegateMyFunction.Instance(UpdateDateTime);
}
else
{
Response.Write(DelegateMyFunction.NowTime);
Response.End();
}
}
}
public DateTime UpdateDateTime()
{
return DateTime.Now;
}
}
为了看到效果我是做在页面页面的。这个类包括了两部分,一部分是是在初始化页面的时候 单例实例化我们的底层方法(方没有type参数的时候)。第二部分是为了我们前台Ajax调用,输出基类的静态的一个时间,方便在前台看到效果。
UpdateDateTime 则是基类需要去调用的更新数据的方法了。
我们再看看页面时怎么样的
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Dialog/jquery-1.7.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function Button1_onclick() {
$.get("DelegatePage.aspx?type=1&time="+new Date() , function (data) {
$("#TextBox1").val(data);
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" οnclick="return Button1_onclick()" />
<br />
<br />
<br />
更新时间为:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
页面很简单,使用了Jquery,有一个Html按钮,还有一个TextBox放更新的值。按钮触发Ajax,去获取后台的值。同时把值显示在控件里面。