I\'m looking for a simple example of how to implement a factory class, but without the use of a Switch or an If-Then statement. All the examples I can find use one. F
You could make use of custom attributes and reflection.
[PositionType(1)]
class Manager : Position
{
public override string Title
{
get
{ return "Manager"; }
}
}
[PositionType(2)]
class Clerk : Position
{
public override string Title
{
get
{ return "Clerk"; }
}
}
In your factory you could then get all classes that inherit from Position and find the one that has the PositionType attribute with the correct value.
static class Factory
{
public static Position Get(int id)
{
var types = typeof(Position).Assembly.GetTypes()
.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Position)))
.ToList();
Position position = null;
foreach(var type in types)
{
type.GetCustomAttributes();
if(type.PositionId == id)
{
position = Activator.CreateInstance(type) as Position;
break;
}
}
if(position == null)
{
var message = $"Could not find a Position to create for id {id}.";
throw new NotSupportedException(message);
}
return position;
}
}