代理模式(Proxy Pattern)
介绍
为其他对象提供一个代理以控制对这个对象的访问。 示例有一个Message实体类,某对象对它的操作有Insert()和Get()方法,用一个代理来控制对这个对象的访问。MessageModel
using System;using System.Collections.Generic;using System.Text;namespace Pattern.Proxy{ ////// Message实体类 /// public class MessageModel { ////// 构造函数 /// /// Message内容 /// Message发布时间 public MessageModel(string msg, DateTime pt) { this._message = msg; this._publishTime = pt; } private string _message; ////// Message内容 /// public string Message { get { return _message; } set { _message = value; } } private DateTime _publishTime; ////// Message发布时间 /// public DateTime PublishTime { get { return _publishTime; } set { _publishTime = value; } } }}
IMessage
using System;using System.Collections.Generic;using System.Text;namespace Pattern.Proxy{ ////// 对Message操作的接口 /// public interface IMessage { ////// 获取Message /// ///List Get(); /// /// 插入Message /// /// Message实体对象 ///bool Insert(MessageModel mm); }}
SqlMessage
using System;using System.Collections.Generic;using System.Text;namespace Pattern.Proxy{ ////// Sql方式操作Message /// public class SqlMessage : IMessage { ////// 获取Message /// ///public List Get() { List l = new List (); l.Add(new MessageModel("SQL方式获取Message", DateTime.Now)); return l; } /// /// 插入Message /// /// Message实体对象 ///public bool Insert(MessageModel mm) { // 代码略 return true; } }}
MessageProxy
using System;using System.Collections.Generic;using System.Text;namespace Pattern.Proxy{ ////// 代理类 /// public class MessageProxy : IMessage { SqlMessage _sqlMessage; ////// 构造函数 /// public MessageProxy() { _sqlMessage = new SqlMessage(); } ////// 获取Message /// ///public List Get() { return _sqlMessage.Get(); } /// /// 插入Message /// /// Message实体对象 ///public bool Insert(MessageModel mm) { return _sqlMessage.Insert(mm); } }}
Client
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using Pattern.Proxy;public partial class Proxy : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { MessageProxy m = new MessageProxy(); Response.Write(m.Insert(new MessageModel("插入", DateTime.Now))); Response.Write(""); Response.Write(m.Get()[0].Message + " " + m.Get()[0].PublishTime.ToString()); }}
运行结果
True SQL方式获取Message 2007-4-1 16:31:24