如何重构这些锁

本文关键字:重构 何重构 | 更新日期: 2023-09-27 18:23:43

将锁移动到Parent类的初始解决方案具有不同的行为:我将无法同时调用new Child1().Method1()new Child2().Method1()

有什么方法可以重构下面的代码吗?

abstract class Parent
{
    protected abstract Method1();
}
class Child1 : Parent
{
    static object staticLock = new object();
    public void Method1()
    {
        lock(staticLock)
        {
          // Do something ...
        }
    }
}
class Child2 : Parent
{
    static object staticLock = new object();
    public void Method1()
    {
        lock(staticLock)
        {
          // Do something else ...
        }
    }
}

我之所以这么问,是因为这不仅仅是两个儿童班,所以真正的问题更大。

如何重构这些锁

让每个子类实现一个方法,该方法提供锁策略,并将Method1移动到基类,如您的另一个问题中所述。

class Parent
{
  public void Method1()
  {
    using(acquireLock())
    {
      Method1Impl();
    }
  }
  protected abstract IDisposable acquireLock();
  protected abstract void Method1Impl();
}
class Child : Parent
{
   protected override IDisposable acquireLock()
   {
      // return some class that does appropriate locking 
      // and in Dispose releases the lock.
      // may even be no-op locking.
   }
}

也许这对有效

abstract class Parent
{
    protected abstract object StaticLock { get; }
    public void Method()
    {
        lock(staticLock)
        {
            MethodImpl();
        }
    }
    protected abstract MethodImpl();
}
class Child1 : Parent
{
    private static object staticLock = new object();
    protected override object StaticLock { get { return staticLock; } }
    protected override MethodImpl()
    {
          // Do something ...
    }
}
class Child2 : Parent
{
    private static object staticLock = new object();
    protected override object StaticLock { get { return staticLock; } }
    protected override MethodImpl()
    {
          // Do something else ...
    }
}