1

我有 3 个类,每个类都可以单独继承以获得某些继承的能力。

但是其中 2 个类可以继承到第 3 个类中,以创建一个“超级”类,其中包括其他 2 个类的能力及其默认逻辑实现。

保持编码逻辑集中的最佳方法是什么?

正如您将在下面看到的,Class2它是我内置的内容的提炼形式Class3。我想在一个位置实现属性的验证逻辑,而不是开发一个接口并且必须为每个实现一遍又一遍地实现逻辑。

有一种情况,Class2既可以单独使用,也可以与Class1. 每个类都有自己独特的用途,但Class3结合了2&1以实现结合两个类功能的最终实现。

课程:
public mustinherit class Class1(of T as {New, Component})
  private _prop as T

  public sub New()
    ...
  end sub

  protected friend readonly property Prop1 as T
    Get
      ..validation..
      return me._prop
    end get
  end property
end class

public mustinherit class Class2
  private _prop as short

  public sub new(val as short)
    me._prop = val
  end sub

  protected friend readonly property Prop2 as short
    get
      return me._prop
    end get
  end property
end class
当前 Class3 实现:
public mustinherit class Class3(of T as {New, Component})
  Inherits Class1(of T)

  'Distilled the logic design below into its own MustInherit class cause this design
  '  by itself is useful without Clas1 implementation.
  private _prop as Short  <--- Same as Class2._prop

  public sub New(val as short)
    me._prop = val
  end sub

  protected friend readonly property Prop2 as short
    get
      return me._prop
    end get
  end property
end class

每@Servy:

第一类
public mustinherit class Data(of T as {New, Component})
...
end class
2 类
public mustinherit class Brand
...
end class
三级
public mustinherit class BrandData(of T as {New, Component})
  inherits Data(Of T)
...
end class
4

1 回答 1

1

我想在一个位置实现属性的验证逻辑,而不是开发一个接口并且必须为每个实现一遍又一遍地实现逻辑。

无需一遍又一遍地实现接口。您必须立即实现验证逻辑,然后将其注入需要验证的类。

interface IValidationLogic
{}

class Class1
{
    protected readonly IValidationLogic _validationLogic;
    public Class1(IValidationLogicvalidationLogic)
    {
        _validationLogic = validationLogic;
    }
}

class Class2
{
    protected readonly IValidationLogic _validationLogic;
    public Class2(IValidationLogicvalidationLogic)
    {
        _validationLogic = validationLogic;
    }
}

class Class3 : Class2
{
    public Class2(IValidationLogicvalidationLogic)
         : base(validationLogic) 
    {}
}


class MyValidationLogic : IValidationLogic
{}


var obj = new Class3(new MyValidationLogic())
于 2013-01-23T16:54:23.113 回答