zoukankan      html  css  js  c++  java
  • 通过代理为对象添加功能

    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本质论>>第七章! 

  • 相关阅读:
    oracle 锁表查看与解锁
    oracle 监视索引是否使用
    oracle 查看数据库版本
    mybatis 中文做参数报错
    windows mysql绿色版配置
    maven使用本地jar包
    Java 使用Jedis连接Redis数据库(-)
    Linux 安装redis
    ELK之在CentOS7.5上使用rpm包安装配置ELK7版本
    Ubuntu-18.04更改安装源为国内源
  • 原文地址:https://www.cnblogs.com/xhan/p/871090.html
Copyright © 2011-2022 走看看