Visual Studio 多态的正确使用和代码重构问题

e0bqpujr  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(173)

我有一个管理PLC变量的桌面应用程序。对于PLC上的读/写,我使用一个名为PLCService的静态类

public static class PLCService 
{ 
   private Plc _plc;

   public void WriteConfiguration(Configuration config)
   {
       ////something to do
   }

   public int[] GetWeightTestValues()
   { 
     return _plc.Read()....
   }
}

现在,问题是:我们还想将此代码用于新机器。这台新机器与原机器相比只做了一点点更改,我必须添加方法并更改静态类的一些方法实现。最后,我想将此应用程序用于机器A和机器B。当应用程序启动时,应用程序转到INI文件,获取机器模型,PLCService需要使用正确的方法实现。
我的第一个想法是在static类中引入一个属性,如下所示:

public static class PLCService
{
    internal static SizerPLC Client;

    public static ProgramMode ProgramMode { get; private set; }

    public static void Init(ProgramMode programMode)
    {
        ProgramMode = programMode;
    }

    public static void Connect(string ipAddress)
    {
        if (ProgramMode == ProgramMode.Angurie)
            Client = new SizerAnguriePLC(ipAddress);
        else if (ProgramMode == ProgramMode.WagonSizer)
            Client = new WagonSizerPLC(ipAddress);
    }

但是我不喜欢这个解决方案,而且我确信这不是正确的解决方案,因为我需要重新实现所有的静态类方法,而且代码开始变得冗余:

public static class PLCService
{
    internal static SizerPLC Client;

    public static ProgramMode ProgramMode { get; private set; }

   
    public static int[] ReadWeightTestValues()
    {
        SizerPLc.ReadWeightTestValues();
    }

你有什么解决办法吗?我在软件开发方面没有太多的经验。

nkhmeac6

nkhmeac61#

您的解决方案:引入属性确实解决了这个问题,但是会导致冗余代码。
使用抽象和继承。您可以创建一个抽象基类或接口来定义PLCService的通用功能,并使用此基类或接口创建两个具体实现,每个实现代表一个不同的机器模型。
创建接口:IPLC服务

public interface IPLCService
{
    void WriteConfiguration(Configuration config);   
    int[] GetWeightTestValues();
}

Implement this interface for each machine model: SizerAnguriePLC 和WagonSizerPLC

public class SizerAnguriePLC : IPLCService 
{
   private Plc _plc;

   public void WriteConfiguration(Configuration config)
   {
       ////something to do
   }

   public int[] GetWeightTestValues()
   { 
     return _plc.Read()....
   }
}

public class WagonSizerPLC : IPLCService 
{
   private Plc _plc;

   public void WriteConfiguration(Configuration config)
   {
       ////something to do
   }

   public int[] GetWeightTestValues()
   { 
     return _plc.Read()....
   }
}

完成机器模型,示例化相应的实现,并赋给IPLCService类型的变量,通过该变量可以访问IPLCService接口的方法。

public static class PLCService
{
    private static IPLCService _plcService;

    public static void Init(ProgramMode programMode,string ipAddress)
    {
        if (programMode == ProgramMode.Angurie)
            _plcService = new SizerAnguriePLC(ipAddress);
        else if (programMode == ProgramMode.WagonSizer)
            _plcService = new WagonSizerPLC(ipAddress);
    }

    public static int[] ReadWeightTestValues()
    {
        return _plcService.GetWeightTestValues();
    }
}

要根据此代码进行更改,可以参考abstraction and inheritance.

相关问题