如何在C#中“包装”实现

时间:2010-03-19 14:45:44

标签: c# design-patterns oop class-design

我在C#(.NET Framework 3.5)中有这些类,如下所述:

public class Base
{
   public int State {get; set;}

   public virtual int Method1(){}
   public virtual string Method2(){}
   ...
   public virtual void Method10(){}
}


public class B: Base
{ 
  // some implementation
}

public class Proxy: Base
{
   private B _b;
   public Proxy(B b) { _b = b; }

   public override  int Method1()
   {
      if (State == Running)
         return _b.Method1();
      else 
         return base.Method1();

   }


   public override  string Method2()
   {
      if (State == Running)
         return _b.Method2();
      else 
         return base.Method2();

   }


    public override  void Method10()
   {
      if (State == Running)
         _b.Method10();
      else 
         base.Method10();
   }
}

我希望得到一些

public Base GetStateDependentImplementation()
{ 
   if (State == Running) // may be some other rule
     return _b;
   else 
     return base; // compile error
}

,我的代理服务器的实施将

public class Proxy: Base
{
   ...
   public override  int Method1()
   {
      return GetStateDependentImplementation().Method1();
   }


    public override string Method2()
   {
      return GetStateDependentImplementation().Method2();
   }
   ...
}

当然,我可以这样做(基础实现的聚合):

 public RepeaterOfBase: Base // no any overrides, just inheritance
    { }

public class Proxy: Base
{
   private B _b;
   private RepeaterOfBase _Base;

    public Proxy(B b, RepeaterOfBase aBase) 
    { 
      _b = b; 
      _base = aBase; 
    }
}

...
     public Base GetStateDependentImplementation()
    { 
       if (State == Running)
         return _b;
       else 
         return _Base; 
    }
...

但Base类的实例非常庞大,我必须避免在内存中有其他额外的副本。

所以我

  • 必须简化我的代码
  • 必须“包装”实施
  • 必须避免代码重复
  • 必须避免任何附加的聚合 基类的实例(复制)

是否有可能实现这些目标?

2 个答案:

答案 0 :(得分:2)

一种解决方案是将昂贵的状态提取到自己的类中,并在具体实现之间共享它的实例。

答案 1 :(得分:0)

您可以将代理对象隐式转换为Base,如下所示:

public class BaseProxy
{
   private Base _base;
   private B _runningBase;

   public BaseProxy(B b)
   {
      _base = new Base();
      _runningBase = b; 
   }

   public static implicit operator Base(BaseProxy proxy)
   {
      return (State == Running) ? proxy._runningBase : proxy._base;
   }
}

这将允许您的客户端代码获取对底层对象的引用(因此它不是完全绝缘的),但它允许您访问代理并使方法按预期运行。


注意:这实际上并不像我想的那样允许隐式使用。