通过代理为对象添加功能

using System;
using System.Threading;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting;

namespace ConsoleApplication1
{
    public interface ICalculator
    {
        double Add(double x, double y);
        double Multiply(double x, double y);
    }


    public class PriortyProxy:RealProxy//定义增加优先级的代理类
    {
        readonly MarshalByRefObject target;
        readonly ThreadPriority level;
        public PriortyProxy(MarshalByRefObject target, Type type, ThreadPriority level):base(type)
        {
            this.target = target;
            this.level = level;
        }
        public override IMessage Invoke(IMessage request)
        {
            IMethodCallMessage call=(IMethodCallMessage)request;
           //调整优先级
            Thread here = Thread.CurrentThread;
            ThreadPriority old = here.Priority;
            here.Priority = level;
         //转发调用
            IMessage response = RemotingServices.ExecuteMessage(target, call);
         //回复为旧的优先级
            here.Priority = old;
         // 将响应消息返回给透明代理
            return response;
        }
    }

    public class MyCalc : MarshalByRefObject, ICalculator
    {
        public static MyCalc Create(ThreadPriority level)//创建插入代理的工厂方法
        {
            MyCalc target = new MyCalc();
            PriortyProxy rp = new PriortyProxy(target, typeof(MyCalc), level);
            return (MyCalc)rp.GetTransparentProxy();
        }
        private MyCalc() { }
        public double Add(double x, double y) { return x + y; }
        public double Multiply(double x, double y) { return x * y; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyCalc c = MyCalc.Create(ThreadPriority.Highest);
            Console.WriteLine(c.Add(1.0, 3.34));
            Console.WriteLine(c.Multiply(2.0, 3.14));
            Console.ReadLine();
        }
    }
}
上述例子为MyCalc类的方法调用实现线程优先级的调整。将优先级调整代码从MyCalc类中分离了出来,但是这并不是透明的。MyCalc必须些一个工厂方法!也必须使用该方法。不能直接用new来创建MyCalc!
上面的例子来自<<.net本质论>>第七章! 

你可能感兴趣的:(对象)