我想知道我是否应该更改我的其中一个项目的软件架构。
我正在为一个项目开发软件,其中双方(实际上是主机和设备)使用共享代码。这有帮助,因为共享数据,例如枚举可以存储在一个中央位置。
我正在使用我们所说的“ channel ”在设备和主机之间传输数据。每个 channel 都必须在设备和主机端实现。我们有不同类型的 channel ,普通 channel 和传输测量数据的专用 channel 。
我当前的解决方案在抽象基类中具有共享代码。从那里开始,代码在双方之间 split 。事实证明,在某些情况下,我们本来可以共享代码但无法共享,因此我们必须在每一方都实现它。
DRY(不要重复自己)的原则说你不应该有两次代码。
我现在的想法是连接例如具有共享代码的抽象类中的设备端和主机端的抽象测量 channel 。这意味着,一旦我们为该 channel 的设备端或主机端创建了一个实际类,我们就必须隐藏另一端使用的功能。
这是可以接受的事情吗:
public abstract class ChannelAbstract
{
protected void ChannelAbstractMethodUsedByDeviceSide() { }
protected void ChannelAbstractMethodUsedByHostSide() { }
}
public abstract class MeasurementChannelAbstract : ChannelAbstract
{
protected void MeasurementChannelAbstractMethodUsedByDeviceSide() { }
protected void MeasurementChannelAbstractMethodUsedByHostSide() { }
}
public class DeviceMeasurementChannel : MeasurementChannelAbstract
{
public new void MeasurementChannelAbstractMethodUsedByDeviceSide()
{
base.MeasurementChannelAbstractMethodUsedByDeviceSide();
}
public new void ChannelAbstractMethodUsedByDeviceSide()
{
base.ChannelAbstractMethodUsedByDeviceSide();
}
}
public class HostMeasurementChannel : MeasurementChannelAbstract
{
public new void MeasurementChannelAbstractMethodUsedByHostSide()
{
base.MeasurementChannelAbstractMethodUsedByHostSide();
}
public new void ChannelAbstractMethodUsedByHostSide()
{
base.ChannelAbstractMethodUsedByHostSide();
}
}
现在,DeviceMeasurementChannel
仅使用来自 MeasurementChannelAbstract
的设备端功能。通过声明 MeasurementChannelAbstract 的所有方法/成员 protected
,您必须使用 new
关键字来启用从外部访问该功能。
这是否可以接受,或者在以后使用代码时是否会出现任何陷阱、注意事项等?
最佳答案
你可以用继承来解决这个问题,像这样:
public abstract class MeasurementChannelAbstract
{
protected abstract void Method();
}
public class DeviceMeasurementChannel : MeasurementChannelAbstract
{
public void Method()
{
// Device side implementation here.
}
}
public class HostMeasurementChannel : MeasurementChannelAbstract
{
public void Method()
{
// Host side implementation here.
}
}
... 或者通过组合,使用 Strategy 模式,像这样:
public class MeasurementChannel
{
private MeasurementStrategyAbstract m_strategy;
public MeasurementChannel(MeasurementStrategyAbstract strategy)
{
m_strategy = strategy;
}
protected void Method()
{
m_strategy.Measure();
}
}
public abstract class MeasurementStrategyAbstract
{
protected abstract void Measure();
}
public class DeviceMeasurementStrategy : MeasurementStrategyAbstract
{
public void Measure()
{
// Device side implementation here.
}
}
public class HostMeasurementStrategy : MeasurementStrategyAbstract
{
public void Measure()
{
// Host side implementation here.
}
}
在我看来,您想在两个标准/测量 channel 和设备/主机 channel 之间划分您的继承层次结构。一种方法是使用多重继承 - 但 C# 不支持多重继承(接口(interface)除外),并且在大多数情况下,基于组合的设计会更简单。
关于c# - 取消不使用的继承功能是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2651562/