像发帖人一样,我也对工厂方法以及如何应用它感到困惑。 看起来工厂方法是为多个具体类提供的,这些类具有与抽象基类完全相同的实现,并且没有添加自己的属性。 但是,正如您将在下面看到的,我的具体类建立在抽象基类之上,并添加了额外的属性。
我们构建的基类:
public abstract class FlatScreenTV
{
public string Size { get; set; }
public string ScreenType { get; set; }
}
扩展类示例:
public class PhillipsFlatScreenTV : FlatScreenTV
{
// Specific to Phillips TVs. Controls the backlight intensity of the LCD screen.
public double BackLightIntensity { get; set; }
}
public class SamsungFlatScreenTV : FlatScreenTV
{
// Specific to Samsung TVs. Controls the time until the TV automatically turns off.
public int AutoShutdownTime { get; set; }
}
假设有更多品牌的平板电视需要扩展类。然后,我们将它们全部放入一个通用列表中:
public static void Main()
{
List<FlatScreenTV> tvList = new List<FlatScreenTV>();
tvList.Add(new PhillipsFlatScreenTV());
tvList.Add(new SamsungFlatScreenTV());
tvList.Add(new SharpFlatScreenTV());
tvList.Add(new VizioFlatScreenTV());
FlatScreenTV tv = tvList[9]; // Randomly get one TV out of our huge list
}
问题:
我想访问这个变量所属的“原始”品牌电视的特定属性。我知道品牌是因为如果我调用tv.GetType()
,它会返回正确的“原始”类型 - 而不是FlatScreenTV
。但我需要能够将tv
从FlatScreenTV
转换回其原始类型,以便能够访问每个品牌的平板电视的特定属性。
问题#1:如何动态地进行强制转换,而不是使用临时方法和巨大的if-else链来猜测“原始”类型?
在浏览类似的设计问题后,大多数答案是:你不能。有些人说要看工厂模式,而其他人则说要使用接口修改设计,但我不知道如何使用它们来解决这个问题。
问题#2:那么,我应该如何设计这些类,以便在上下文中访问原始类型的特定属性?
问题#3:这真的是不好的继承吗?