13.代理模式(Proxy Pattern)

using System;

namespace Test
{
    //抽象角色:声明真实对象和代理对象的共同接口。
    //代理角色:代理对象角色内部含有对真实对象的引用,从而可以操作真实对象,
    //同时代理对象提供与真实对象相同的接口以便在任何时刻都能代替真实对象。
    //同时,代理对象可以在执行真实对象操作时,附加其他的操作,相当于对真实对象进行封装。
    //实角色:代理角色所代表的真实对象,是我们最终要引用的对象。
    //使用场景:当我们需要使用的对象很复杂或者需要很长时间去构造,
    //这时就可以使用代理模式(Proxy)。例如:如果构建一个对象很耗费时间和计算机资源,
    //代理模式(Proxy)允许我们控制这种情况,直到我们需要使用实际的对象。一个代理(Proxy)通常包含和将要使用的对象同样的方法,
    //一旦开始使用这个对象,这些方法将通过代理(Proxy)传递给实际的对象。 一些可以使用代理模式(Proxy)的情况:
    class Program
    {
        static void Main(string[] args)
        {
            ProxyPerson proxy = new ProxyPerson(new Person() { Name = "游客", Power = 3 });
            proxy.Post();
            proxy.Remove();
            proxy.Check();
            proxy.Comment();

            Console.ReadLine();
        }
    }

    // 抽象论坛用户
    public interface IPerson
    {
        string Name { get; set; }
        int Power { get; set; }
        //发帖
        void Post();
        //删贴
        void Remove();
        //审查贴
        void Check();
        //回复贴
        void Comment();
    }

    public class Person : IPerson
    {
        public string Name { get; set; }
        public int Power { get; set; }

        public void Post()
        {
            Console.WriteLine("发帖");
        }

        public void Remove()
        {
            Console.WriteLine("删贴");
        }

        public void Check()
        {
            Console.WriteLine("审查贴");
        }

        public void Comment()
        {
            Console.WriteLine("回复贴");
        }
    }

    // 代理
    public class ProxyPerson : IPerson
    {
        public string Name { get; set; }
        public int Power { get; set; }
        Person RPerson;
        public ProxyPerson(IPerson person)
        {
            this.Name = person.Name;
            this.Power = person.Power;
            RPerson = (Person)person;
        }

        public void Post()
        {
            if (Power < 3)
                RPerson.Post();
            else
                Console.WriteLine("游客不能发帖");
        }

        public void Remove()
        {
            if (Power == 1)
                RPerson.Remove();
            else
                Console.WriteLine("管理员才能删帖");
        }

        public void Check()
        {
            if (Power == 1)
                RPerson.Check();
            else
                Console.WriteLine("管理员才能审查贴");
        }

        public void Comment()
        {
            if (Power < 3)
                RPerson.Post();
            else
                Console.WriteLine("游客不能回复");
        }
    }
}