.net core 设计模式--->代理模式

      什么是代理,说白了就是中介,大学的时候打过暑假工的都应该知道,你要进电子厂打工,中间谁签的线?带你去电子厂,并且能让你进去的那个人就是代理。比如你要买东西,你自己不打算去,让别人帮你买,也是代理。

  废话不多说,写个简单明了的例子,就行了。

   首先要抽象一个角色这个角色是抽象类或者接口都行。下面就写个接口

       

 public interface Workinerface
    {
        //工作类
        void Work(string PersonName);
    }

定义一个真实角色类

 public class Peron : Workinerface
    {
        public void Work(string PersonName)
        {
            Console.WriteLine($"姓名为{PersonName}去了电子厂,做的工作是");
        }
    }

定义一个代理角色

  public class Proxy : Workinerface
    {
      public  PeronClass person;
        public Proxy()
        {
            person = new PeronClass();
        }

        public void Work(string PersonName)
        {
            before();
            person.Work(PersonName);
            after();
        }
        public void before()
        {
            Console.WriteLine("真实角色执行前。。。。");
        }public void after()
        {
            Console.WriteLine("真实角色执行后。。。。");
        }
        
    }

客户端调用:

 class Program
    {
        static void Main(string[] args)
        {
           
            Workinerface work = new Proxy();
            work.Work("张三");
            Console.Read();
        }
       

效果:

 

  代理模式就是这样实现的,是不是很简单。(其实代理模式的好处就是,在真实角色没有执行自己的方法之前和之后可以做一些操作)

  但是后来我又想了想,如果一个代理不止代理一种类型,于是我就改进了一下:

 public interface Workinerface
    {
        //工作类
        void Run(string PersonName);
    }
 
    public class PeronClass : Workinerface
    {
        public void Run(string PersonName)
        {
            Console.WriteLine($"姓名为{PersonName}去了电子厂");
        }
    }
    public class RentHouse : Workinerface
    {
        public void Run(string PersonName)
        {
            Console.WriteLine($"姓名为{PersonName}租了房");
        }
    }

    public class Proxy<T> : Workinerface where T : Workinerface, new()
    {
      public  T t;
        public Proxy()
        {
            t = new T();
        }

        public void Run(string PersonName)
        {
            before();
            t.Run(PersonName);
            after();
        }
        public void before()
        {
            Console.WriteLine("真实角色执行前。。。。");
        }public void after()
        {
            Console.WriteLine("真实角色执行后。。。。");
        }

客户端调用:

 class Program
    {
        static void Main(string[] args)
        {
          
            Workinerface work = new Proxy<PeronClass>();
            Workinerface house = new Proxy<RentHouse>();
            work.Run("张三");
            house.Run("李四");
            Console.Read();
        }

效果:

 

posted @ 2021-03-26 16:32  代码如风~~~  阅读(245)  评论(0编辑  收藏  举报