Singleton + Proxy 模式+AOP

來源:互聯網
上載者:User
在.NET 中,可以通過CBO來實現簡單的一個msg層級的AOP, 可以參考我以前寫的一個簡單例子. 採用AOP 的觀點來 Log 所有方法的調用

昨天正好培訓了一下Remoting, 其實可以用一個realproxy來wrap所有的方法調用,並且可以做一些攔截.為此參考一下簡單的代碼

事實上,包含了singleton,proxy模式,呵呵


    class Demo:MarshalByRefObject
    {
        public void SayHello()
        {
            Console.WriteLine("Hello,China");
        }

        private Demo()
        {
        }

        private static Demo _ActInstance = new Demo();

        public static Demo GetInstance()
        {
            DemoProxy dp = new DemoProxy(typeof(Demo),_ActInstance);
            return (Demo)dp.GetTransparentProxy();            
        }
    }


    class DemoProxy : System.Runtime.Remoting.Proxies.RealProxy
    {
        public DemoProxy(Type tp,Demo target) : base(tp) { _target=target;}

        private Demo _target;

        public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
        {
            Console.WriteLine(">>> Inspecting Msg" + (msg as System.Runtime.Remoting.Messaging.IMethodCallMessage).MethodName); 
            return System.Runtime.Remoting.RemotingServices.ExecuteMessage(_target, (System.Runtime.Remoting.Messaging.IMethodCallMessage)msg);
        }
    }

其實Demo一定要從MBR繼承,參考了don box 寫的.net essential, 他提到了從MBR繼承,.net clr 保證改類的方法不會被inline,這樣就可以保證代理的正常工作.  如果從CBO繼承,當然CBO是繼承自MBR, proxy可以正常工作, 而且這時候new 一個CBO對象的時候,實際上該執行個體就是一個透明代理.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.