I have made a factory function that returns an abstract class bases on enum values. Now my goal is to provide the abstract class for a certain set of enum values and provide the direct class for the other set.
My code:
public Component CreateComponent(string identifier, ComponentType type) => type switch
{
ComponentType.AND => new AndNode(identifier),
ComponentType.NAND => new NAndNode(identifier),
ComponentType.NOR => new NOrNode(identifier),
ComponentType.NOT => new NotNode(identifier),
ComponentType.OR => new OrNode(identifier),
ComponentType.XOR => new XOrNode(identifier),
ComponentType.PROBE => new Probe(identifier),
ComponentType.INPUT_LOW => new InputBit(identifier, 1),
ComponentType.INPUT_HIGH => new InputBit(identifier, 2),
_ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(type))
};
My goal is that every type returns a Component class, but the INPUT_HIGH and INPUT_LOW should provide me with the InputBit class. I can't think of a solution, which doesn't include type checking (dynamic casting or using 'is'). Besides from my understanding C# does not have a template method like C++ does.
Edit: I need a List with all the Components and a List with all the InputBits in the class that calls this function. At the moment I am able to get a list of all the Components like this:
components.Add(factory.CreateComponent(node_description.identifier, type));
I need a list of the InputBits as well. So I can check what the factory returns by type checking, but I'm trying to prevent that. Is there an ideal solution?
Aucun commentaire:
Enregistrer un commentaire