我做了一些控制硬件的功能。但是,如果存在实际硬件(G.demomode = true)
,我也要称呼实现相同接口的实际硬件功能。
您可以在下面看到我的尝试,但是这一行DVDDHW.setSupply(voltage);
不太正确,即因为静态类无法实现接口。有一个更好的方法吗?
最终目标是为硬件工程师定义一个要遵循的接口(也许这不是正确的词),以便他可以在该接口中指定未指定的功能。
我尝试进行搜索的尽职调查,并且发现了与此主题相关的多个主题。但是,我无法全神贯注于如何为用例实现其替代解决方案。任何帮助或指针将是巨大的。
谢谢!
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public static class DVDDHW : IPowerSupply
{
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
如果您只想要实现一个接口的类的一个实例,则可以采用单例方式。
MS的使用方法是https://msdn.microsoft.com/en-us/library/ff650316.aspx。
对于您的代码,以下将起作用:
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public class DVDDHW : IPowerSupply
{
IPowerSupply _instance;
public static IPowerSupply Instance
{
get
{
if (_instance == null)
_instance = new DVDDHW();
return _instance;
}
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
与静态类相比,单例的行为方式略有不同。如果您的应用程序是多线程的,或者在构造函数中还有其他一些您希望在首次访问该类型时首次运行的代码,则这些代码很重要。如果这些东西对您没有任何意义,那么您就不必担心:)
编辑:
正如Scott所指出的,get访问器中的代码是不必要的。简化的版本是这样的:
public class DVDDHW : IPowerSupply
{
static readonly IPowerSupply _instance = DVDDHW();
public static IPowerSupply Instance
{
get { return _instance; }
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
另外,此代码有错别字(固定):
//Code to execute below:
foreach IPowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句