ログインしてさらにmixiを楽しもう

コメントを投稿して情報交換!
更新通知を受け取って、最新情報をゲット!

デザインパターンコミュのNullObjectパターン

  • mixiチェック
  • このエントリーをはてなブックマークに追加
汎用的なNullObjectを提供するプロキシをC#で書きました。
改善点などございましたら、ご教授願います。
http://d.hatena.ne.jp/zecl/20080210/p1


using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Text.RegularExpressions;

namespace WindowsApplication1
{
  /// <summary>
  /// ジェネリックなNullObjectを提供します。
  /// プロキシの基本機能を提供するRealProxyを継承します。
  /// </summary>
  /// <typeparam name="T">
  /// NullObject対象の型を指定します。制約:publicなデフォルトコンストラクタを有するMarshalByRefObject型のクラスであること。
  /// </typeparam>
  public class NullProxy<T> : RealProxy where T : MarshalByRefObject ,new()
  {
    /// <summary>
    /// ジェネリックなSingletonを提供するためのコレクション。
    /// ガベコレで収集されるまでの間の弱い参照を保持します。
    /// </summary>
    private static readonly Dictionary<Type, WeakReference> dicNullObject = new Dictionary<Type, WeakReference>();

    /// <summary>
    /// 排他ロックオブジェクト
    /// </summary>
    static readonly object syncObj = new object();

    /// <summary>
    /// コンストラクタ
    /// </summary>
    public NullProxy() : base(typeof(T)) {
    }

    /// <summary>
    /// メソッド呼び出しに割り込んでなにもしません。
    /// メソッドに戻り値がある場合、値型なら初期値を返します。
    /// 参照型の場合、抽象クラスおよびインターフェイスであればnullを返します。
    /// いずれでもなければ、System.MarshalByRefObjectの派生クラスの場合、
    /// NullProxy<T>を通して生成したNullObjectを返します。
    ///
    /// メソッドの引数について、outパラメータおよびrefパラメータである場合、
    /// そのパラメータがSystem.MarshalByRefObjectの派生クラスである場合、
    /// そのパラメータに対して、NullProxy<T>を通して生成したNullObjectを返します。
    /// </summary>
    /// <param name="msg">メッセージ通信オブジェクト</param>
    /// <returns>ReturnMessageオブジェクト</returns>
    public override IMessage Invoke(IMessage msg)
    {
      IMethodCallMessage req = msg as IMethodCallMessage;
      object response = null;

      //メソッドのメタデータを取得
      MethodInfo methodInfo = ((MethodInfo)req.MethodBase);

      //Outパラメータ配列
      ArrayList outList = new ArrayList();

      //メソッドの各パラメータ情報を検索
      foreach (ParameterInfo paramInfo in methodInfo.GetParameters())
      {
        if (paramInfo.ParameterType.IsByRef){
          //out/refパラメータの場合
          //メンバの参照型の型に対する、NullObjectとして適切なインスタンスを取得

          //正規表現でByRef属性を意味する 末尾にある"&" を型の名前から取り除く
          string typeString = paramInfo.ParameterType.ToString();
          Regex regex = new Regex("&$");
          typeString = regex.Replace(typeString, string.Empty);
          
          outList.Add(GetResponceInstance(Type.GetType(typeString)));     
        }
      }
      
      //戻り値の型に対する、NullObjectとして適切なインスタンスを取得
      response = GetResponceInstance(methodInfo.ReturnType);

      //リターンメッセージ
      return new ReturnMessage(response,outList.ToArray(),outList.Count, req.LogicalCallContext, req);
    }

    /// <summary>
    /// 対象の型について、NullObjectとして返す適切なインスタンスを取得します。
    /// </summary>
    /// <param name="t">対象の型</param>
    /// <returns>NullObjectとして返す適切なインスタンスを取得します。</returns>
    private object GetResponceInstance(Type t){
      object response = null;

      if (t.IsValueType)
      {
        //値型の場合
        if (t != typeof(void))
        {
          //戻り値がある場合
          response = Activator.CreateInstance(t);
        }
      }else{
        //参照型の場合
        
        if (t != typeof(void))
        {
          //voidではない場合
          
          //抽象クラス、あるいはインターフェイスであればnullを返す
          if (t.IsAbstract || t.IsInterface) { return null; }

          if (t.IsMarshalByRef)
          {
            //参照渡しでマーシャリングされる場合

            //NullProxy<>の型を取得
            Type genericType = typeof(NullProxy<>);
            //NullProxyに必要なジェネリック型を生成
            Type constructGenericType = genericType.MakeGenericType(new Type[] { t });
            //要求されているNullProxy<>インスタンスを生成
            object nullproxy = Activator.CreateInstance(constructGenericType);

            //リフレクションを利用してNullObjectを生成
            response = nullproxy.GetType().InvokeMember("GetInstance", BindingFlags.InvokeMethod, null, response, null);
          }
        }
      }    
      return response;
    }

    /// <summary>
    /// 対象の型のNullObjectインスタンスを取得します。
    /// 各型のNullObjectインスタンスは、ガベコレで収集されるまでの間Singletonで提供されます。
    /// </summary>
    /// <returns>対象の型のNullObjectインスタンス</returns>
    public static T GetInstance()
    {
      lock (syncObj)
      {
        NullProxy<T> result = null;
        Type t = typeof(T);

        //ガベコレ対象のまま参照します。
        WeakReference w = dicNullObject.ContainsKey(t) ? dicNullObject[t] : null;

        if (w != null){
          result = w.Target as NullProxy<T>;
        }
        
        if (result == null)
        {
          result = new NullProxy<T>();
          
          dicNullObject[t] = new WeakReference(result,true);
        }

        // NullObject対象の型の透過プロキシを返します。
        return (T)result.GetTransparentProxy();
      }
    }
  }
}

コメント(0)

mixiユーザー
ログインしてコメントしよう!

デザインパターン 更新情報

デザインパターンのメンバーはこんなコミュニティにも参加しています

星印の数は、共通して参加しているメンバーが多いほど増えます。