更新时间:2023-02-15 15:36:29
由于 USBCommunicator
管理所有重要资源(包括流的生命周期),应用程序应调用 USBCommunicator.Send
,而不是 Report.Send
:
Since USBCommunicator
manages all the important resources (including the stream's lifetime), applications should call USBCommunicator.Send
, not Report.Send
:
public class USBCommunicator {
public void Send(Report report) {
// If it's appropriate, this method can also Open
// and Close the stream so callers don't have to.
report.Send(this.stream);
}
}
发送 internal,因此它不是公共API的一部分,应用程序可以这样做:
Next, make Report.Send
internal so it isn't part of the public API, and applications can do this:
public void main(string[] args) {
USBCommunicator myUSB = new USBCommunicator("15B3");
myUSB.SerialNumber = "123ABC";
myUSB.OpenConnection();
Report report = new Report(3, 1000, "Send this Data");
myUSB.Send(report);
}
我不认为除了
之外的任何类USBCommunicator应该能够
创建一个Report
类的实例。
I don't think any class other than USBCommunicator should be able to create an instance of the Report class.
您当前的设计并不能防止这种情况 - 实际上,您的示例应用程序创建了 Report
类的实例。如果你真的想隐藏报表类,你应该把它私密到 USBCommunicator
,并将其属性推出到通讯器的界面,如下:
Your current design doesn't prevent this - indeed, your sample application is creates an instance of the Report
class. If you really want to hide the report class, you should make it private to USBCommunicator
and push its attributes out to the communicator's interface like this:
// USBCommunicator
public void Send(int reportID, int timeout, string data) {
Report report = new Report(reportID, timeout, data);
report.Send(this.stream);
}