C# 代理模式 ProxySubject.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace ProxyModelDemo
{
    /// <summary>
    /// 代理
    /// 包一层:没有什么技术是包一层不能解决的,如果有,就再包一层
    /// 日志代理:在代理层扩展,
    ///           避免修改业务类
    /// 缓存代理:使用上次的结果,提升性能,
    ///            没有修改业务类
    /// 单例代理:保证类型在进程中只有一个实例,
    ///            没有修改业务类,通过代理类调用,就是一个实例
    /// 延时代理:推迟一切可以推迟的
    ///           网页前端,惰性加载 懒加载 按需加载 滚动加载
    ///           这样可以提升性能,只加载你需要的,其他的先不管
    ///           队列-异步多线程-泛型的设计
    /// 权限代理,用户登陆 数据权限 操作权限  CallContext
    ///           没有修改业务类,通过代理类的扩展,完全权限校验
    /// </summary>
    public class ProxySubject : ISubject
    {
        /// <summary>
        /// static变量:第一次使用到ProxySubject之前,由CLR保证,先初始化这个字段,而且只初始化一次
        /// </summary>
        //private static RealSubject subject = new RealSubject();
        private ISubject subject = null;

        private void Init()
        {
            this.subject = new RealSubject();
        }


        public void DoSomethingLong()
        {
            try
            {
                //日志代理
                Console.WriteLine("Prepare DoSomethingLong");//模拟添加日志新需求//日志代理
                if (this.subject==null) //延时代理,只有立马要使用资源,我们才初始化一下
                {
                    this.Init();
                }
                subject.DoSomethingLong();
            }
            catch (Exception ex)
            {

                throw ex;
            }
            
        }

        public List<string> GetSomethingLong()
        {
            try
            {

                //按照线程,给线程存储数据,字典
                CallContext.SetData("CurrentUser", "Eleven");
                if (CallContext.GetData("CurrentUser")==null 
                    || !"Eleven".Equals(CallContext.GetData("CurrentUser").ToString())) //权限代理
                {
                    throw new Exception("用户无权登陆");
                }

                Console.WriteLine("Prepare GetSomethingLong");//模拟添加日志新需求//日志代理
                string key = $"{nameof(ProxySubject)}_{nameof(GetSomethingLong)}";
                List<string> result = null;
                if (!CustomCache.Exists(key))
                {
                    if (this.subject == null) //延时代理
                    {
                        this.Init();
                    }
                    result = subject.GetSomethingLong();
                    CustomCache.Add(key, result);//模拟添加缓存//缓存代理
                }
                else
                {
                    result = CustomCache.Get<List<string>>(key);//模拟读取缓存//缓存代理
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/89428676