I previously posted this one , but I think it was too verbose and inappropriate. My question is also similar to this . One poster in the second link said that the answer (why can't you make the code below) was a design issue, in particular the “poor use of inheritance”. Therefore, I would like to check this problem again with the experts at StackOverflow and see if this is really a bad inheritance problem, but more importantly, how to fix the design.
Like the poster, I am also confused about the Factory method and how I can apply it. It seems the Factory method is intended for several specific classes that have the same implementation as the abstract base class and do not add their own properties . But, as you will see below, my specific classes are based on an abstract base class and add additional properties .
The base class that we will build on:
public abstract class FlatScreenTV { public string Size { get; set; } public string ScreenType { get; set; } }
Examples of extension classes:
public class PhillipsFlatScreenTV : FlatScreenTV {
Suppose there are more extension classes for more flat screen TVs. And then, let's say we insert them all into a general list:
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];
Problem:
I want to access the specific properties of any "original" brand to which this variable belongs. I know the brand because if I call tv.GetType() , it returns the correct "original" type - not FlatScreenTV . But I need to be able to tv from FlatScreenTV to return to the original type in order to be able to access the specific properties of each brand of flat-screen TVs.
Question No. 1: How can I dynamically cast this, correctly - without temporary hacks and huge if-else chains, to roughly guess the type of "original"?
After looking at similar design problems, most of the answers are: you cannot . Some people say to look at the Factory template, while others say that you need to revise the design using interfaces, but I don’t know how to use either to solve this problem.
Question # 2: So, how do I create these classes so that I can access the original properties of the type in the context above?
Question # 3: Is this really bad inheritance?