会打破SOLID原则吗?

问题描述 投票:0回答:1

我正在尝试编写一个被调用的通用方法,并根据对象类型设置指示器。

  1. 它会打破任何坚实的原则吗?
  2. 有更好的方法吗?

我正在开发其中一项功能,其中我有 3 条业务线,例如汽车、货车和自行车。

我有

IVehicle
接口,用于处理 3 个业务线之间的所有常见实现。

现在,我必须设置两个通用指示器

Car
Van
,但是对于
Bike
,我想设置一些不同的指示器。我想创建一次此类的对象,但它根据线路业务类型进行处理。

如果这样写这个方法会破坏任何SOLID原则吗?如果不正确,您能提出替代方案吗?

注意:

INDICATOR_B
在所有LOB中都应该为真

function populateIndicator() {
  if (_motorObject typeis Car or _motorObject typeis entity.Van) {
    _motorObject.INDICATOR_A = true
  }

  if (_motorObject typeis Bike) {
    _motorObject.INDICATOR_C = true
  }

  _motorObject.INDICATOR_B = true
}
oop generics design-patterns solid-principles gosu
1个回答
0
投票

简短版本:使用多态性来实现

populateIndicator
方法。

检查基类中的类型违反了 Liskove 替换原则。如果您有重复的分配代码,例如

_motorObject.INDICATOR_B = true
,您可以使用模板方法模式。

abstract class VehicleBase{

   public void populateIndicator(){

      conceretePopulateIndicator();
      // common code for all derived classes
      _motorObject.INDICATOR_B = true;
   }

   protected abstract void conceretePopulateIndicator();

}

public class Bike: VehicleBase{

    protected override void conceretePopulateIndicator(){
        _motorObject.INDICATOR_C = true
    } 
}

这个设计不会违反任何规则。

© www.soinside.com 2019 - 2024. All rights reserved.