Tim*_*sig 9 c# architecture oop
我想知道是否应该改变我的一个项目的软件架构.
我正在为一个项目开发软件,其中双方(实际上是主机和设备)使用共享代码.这有助于共享数据,例如枚举可以存储在一个中心位置.
我正在使用我们称之为"通道"的设备和主机之间传输数据.每个通道必须在设备和主机端实现.我们有不同类型的通道,普通通道和传输测量数据的特殊通道.
我当前的解决方案在抽象基类中具有共享代码.从那里开始,代码在双方之间分开.事实证明,在某些情况下,当我们共享代码但我们无法共享代码时,我们必须在每一方面实现它.
DRY的原则(不要重复自己)说你不应该有两次代码.
我的想法是现在连接例如设备端的抽象测量通道和具有共享代码的抽象类中的主机端的功能.这意味着,一旦我们为该通道创建设备或主机端的实际类,我们就必须隐藏另一方使用的功能.
这是可以接受的事情:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,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.
}
}
Run Code Online (Sandbox Code Playgroud)
......或通过组合,使用策略模式,如下所示:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,要分之间的继承层次两个标准/测量通道和设备/主机通道.一种方法是使用多重继承 - 但C#不支持多重继承(接口除外),并且在大多数情况下,基于组合的设计将更简单.
对我来说,它看起来有点像你混淆继承和组成.当继承的功能没有明显重叠时,你必须"空白"/抛出异常,你的继承图缺少一些中间类.通常这是因为某些功能应该来自其他类的成员实例而不是继承.
考虑到实用性,将所有内容映射到完美的OOP不是目标,目标是一个可维护而没有巨大痛苦的工作程序.