首页 > 代码库 > 设计模式之代理模式

设计模式之代理模式

理解如下:

  1. 客户端不能直接调用具体的业务类时可以使用代理类.
  2. 代理类和业务类重同一接口继承下来.
  3. 代理类调用业务类,客户端调用代理类.

接口代码:

 /// <summary>    /// 定义客户端调用的目标对象的接口    /// </summary>    public interface IPlayMusic    {        string PlayMusic(string musicType);    }

 业务类代码:

public class PlaySubject:IPlayMusic    {        private static readonly PlaySubject instance = new PlaySubject();        private PlaySubject()        {                     }        public static IPlayMusic PlaySuject        {            get            {                return instance;            }        }                #region IPlayMusic 成员        public string PlayMusic(string musicType)        {            if (musicType == "mp3")            {                return "mp3";            }            else            {                return "other";            }        }        #endregion    }

代理类代码:

 public class PlayMusicProxy:IPlayMusic    {        #region IPlayMusic 成员        public string PlayMusic(string musicType)        {            return PlaySubject.PlaySuject.PlayMusic(musicType);        }        #endregion    }

客户段代码:

 PlayMusicProxy proxy = new PlayMusicProxy();            string str;            str = proxy.PlayMusic("mp3");            Response.Write(str); 

问题:

看来看去好象作用不大,好处是什么?代理类封装了业务逻辑,简化了客户端代码?

设计模式之代理模式