我必须实现配电盘类,该类可以具有风扇,交流电,灯泡等设备。我的配电盘类如下所示。
哪一个是面向对象的?
1。
class SwitchBoard
{
public static int totalDevices=0;
public List<ElectricDevice> Devices { get; set; }
public SwitchBoard(int noOfFans, int noOfACs, int noOfBulbs)
{
Devices = new List<ElectricDevice>();
//int deviceCount = 0;
for (int i = 0; i < noOfACs + noOfBulbs + noOfFans; i++)
{
if (i < noOfFans)
{
Devices.Add(new Fan("Fan " + (i + 1),totalDevices));
}
else if (i >= noOfFans && i < noOfFans + noOfACs)
{
Devices.Add(new AC("AC " + (i - noOfFans + 1), totalDevices));
}
else
{
Devices.Add(new Bulb("Bulb " + (i - noOfFans - noOfACs + 1), totalDevices));
}
totalDevices++;
}
}
}
2。
class SwitchBoard
{
public static int totalDevices=0;
public List<ElectricDevice> Devices { get; set; }
public SwitchBoard(int noOfFans, int noOfACs, int noOfBulbs)
{
Devices = new List<ElectricDevice>();
CreateDevice(Devices, "Fan", noOfFans);
CreateDevice(Devices, "AC", noOfACs);
CreateDevice(Devices, "Bulb", noOfBulbs);
}
我觉得第一种方法是最好的方法,因为在第二种方法中,我们使用的方法是通过在类之外获取属性并在其外部实例化来实例化该类。就像从开关板上取出开关并将其连接到风扇并将其放回到开关板上一样。
我认为这与封装有关。
CreateDevice的伪代码
function CreateDevice(List<EelectricDevice> Devices, string type, int noOfObjects )
{
for(int i=Devices.Length; i<noOfDevices+Devices.Length;i++)
{
if(type=="Fan")
Device[i]=new Fan("Fan"+i);
else if(type=="AC")
Device[i]=new AC("AC"+i);
else if(type=="Bulb")
Device[i]=new Bulb("Bulb"+i);
}
}
系统设计很难建议,因为有很多事情需要考虑。
但是,将其保持在最低限度并坚持您的问题,有几件事需要考虑-
建议有一个interface
类似的东西ISwitchable
,可以由ElectricDevice实现,并且可以切换。从概念上讲,这很重要,因为并非所有的ElectricDevices都是可切换的-
public interface ISwitchable
{
}
现在,您可以在设备中实现以下功能-
public class Fan : ElectricDevice, ISwitchable
{
//Implementation of fan
}
对于设备总数,应将其实现为只读属性,该属性是所有设备的总和,否则该值可能会被篡改。无需每次迭代都计算该值。
最后,这就是您的SwitchBoard
课程外观-
public class SwitchBoard
{
public List<ISwitchable> switchableDevices { get; private set; }
public int TotalSwichableDevices
{
get { return numberOfFans + numberOfACs + numberOfBulbs; }
}
private readonly int numberOfFans;
private readonly int numberOfACs;
private readonly int numberOfBulbs;
public SwitchBoard(int noOfFans, int noOfACs, int noOfBulbs)
{
this.numberOfFans = noOfFans;
this.numberOfACs = noOfACs;
this.numberOfBulbs = noOfBulbs;
switchableDevices = new List<ISwitchable>();
switchableDevices.AddRange(this.AddFans());
//TODO: Add other devices
}
private IEnumerable<ISwitchable> AddFans()
{
List<ISwitchable> fans = new List<ISwitchable>();
for (int i = 0; i < numberOfFans; i++)
{
fans.Add(new Fan());
}
return fans;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句