我試圖找出我是否正在以正確的方式查看遏制/委派。在這個例子中,我有一個Car
和一個Radio
類型。我有一個函數,它接受一個字符串並更改Radio對象的IsOn
屬性的值。我想知道哪種方法(或兩種方法)是否能夠解決此問題的充分方法。正確地將請求委託給內部對象
(請忽略呼入串入所述開啓方法的驗證,爲簡單起見)
public int Year { get; set; }
public string Model { get; set; }
protected Radio radio = new Radio();
public Radio MyRadio
{
get { return radio; }
set { radio = value; }
}
public class Radio
{
public string ModelNumber { get; set; }
public bool IsOn { get; set; }
public void TurnOn(string turnOn)
{
if (turnOn == "yes")
{
if (IsOn)
Console.WriteLine("The radio is already on");
else
{
IsOn = true;
Console.WriteLine("You turned on the radio");
}
}
else
{
if (IsOn)
{
IsOn = false;
Console.WriteLine("You turned off the radio");
}
}
}
}
我在主要方法測試此,輸出是在評論的每行的旁邊
Car c = new Car();
Console.WriteLine(c.MyRadio.IsOn); //false
c.MyRadio.TurnOn("yes"); //you turned on the radio
Console.WriteLine(c.MyRadio.IsOn);//true
c.MyRadio.TurnOn("yes"); //the radio is already on
c.MyRadio.TurnOn("no"); //you turned off the radio
Console.WriteLine(c.MyRadio.IsOn); //false
我想到要幹這種添加了以下功能Car類
public void CarChangesState(string s)
{
MyRadio.TurnOn(s);
}
的另一種方法
我用下面的代碼測試它和一切工作按預期
Car c2 = new Car();
Console.WriteLine(c2.MyRadio.IsOn);//false
c2.CarChangesState("yes"); //you turned on the radio
Console.WriteLine(c2.MyRadio.IsOn);//true
c2.CarChangesState("yes");//the radio is already on
c2.CarChangesState("no");//you turned off the radio
Console.WriteLine(c2.MyRadio.IsOn); //false
就是一個例子比其他的更好嗎?從我讀到的Pro C# and the .NET Framework
我有一種感覺,就像第一次迭代不是真正的委派,但我想知道一種方法比另一種方法更少有什麼缺點。
有點偏題:爲什麼你要傳遞一個字符串到ChangeState方法中?更可讀的選項是'bool'。最好的選擇可能是一個'Enum RadioState'。傳遞一個魔術串真的感覺像是「字符串型」反模式。 – dss539
這是個好主意。 – wootscootinboogie