上一个问题(更简单):从另一个类更新类,封装问题
例子:
class User
{
public void BeginWork(Device device)
{
Command command = new Command(1);
device.ExecuteCommand(command);
Console.WriteLine("Result={0}", command.Result);
}
}
class Command
{
public int Code {get; private set;}
public Command(int code) { Code = code; }
public int Result { get; set; }
}
class Device
{
public void ExecuteCommand(Command command)
{
/* ... */
// Analyzing and execution of command leads to a result
if(command.Code == 1) command.Result = 5;
else if(command.Code == 2) command.Result = 36;
/* ... */
}
}
用法:
User u = new User();
Device d = new Device();
u.BeginWork(d);
如您所见,封装被Result
类属性的公共集访问器破坏Command
不建议更改方法ExecuteCommand
返回结果。实际情况要复杂得多。
如何保持封装?