For explanation: I have a code which creates a pattern of symbols (I've got 4 different classes with one pattern each) on the Console
and I want to create a "Factory" to decide which class it should use for that symbol pattern, but I can't create an object of this class.
//doesn't work --> PrinterFactory is an abstract class
PrinterFactory baumPrinterFactory = new PrinterFactory();
//decides which one to get
Baum b1 = new Nadelbaum() { Kronenhoehe = 10, StammHoehe = 9 };
//Baum b1 = new Laubbaum() { Kronenhoehe = 21 };
//Baum b1 = new Weihnachtsbaum() { Kronenhoehe = 15, StammHoehe = 7 };
//Baum b1 = new Obstbaum() { Kronenhoehe = 32 };
//Prints the Pattern
BaumPrinter baumPrinter = new PrinterFactory();
baumPrinterFactory.GetBaumPrinter();
baumPrinter.Print(b1);
You don't say, but I'm assuming that each of the other types derives from PrinterFactory
(eg: public class Nadelbaum : PrinterFactory { ... }
).
Normally you'd use a static
factory method for this.
public abstract class PrinterFactory
{
public static PrinterFactory GetInstance(string instanceType) {
switch (instanceType) {
case "Nadelbaum": return new Nadelbaum();
case "Laubbaum": return new Laubbaum();
// etc
}
}
}
Then you can use:
var printer = PrinterFactory.GetInstance("Nadelbaum");
and printer
will be defined as type PrinterFactory
but actually be an instance of Nadelbaum
.
You didn't specify how you choose which instance type to create, so I just showed and example with strings, but you can of course whatever criteria you can think of to choose the type based on whatever parameters you pass to to the factory method.