I want to use factory pattern in my application where I receive a huge(500k) list , lets say List,of objects and I loop through it, now one of the property(SeatType) decides which class to process that list, so if seat type is premium it is handled by different class and similarly for economy and so on...
class Bus
{
public SeatType Type { get; set; }
}
Since the check on seat type and hence finding the processor is happening inside the loop whats the best way to resolve/find the instance of property which has to process that bus?
I know I can group the list by seat type and then process it, but I am interested to know if there is a better way to do it without grouping and by using just the loop.
Thanks in advance!!!
Edit:
In my case I need the processors at like 5th level, e.g. in for loop I am calling ClassA.MethodA and then MethodA calls ClassB.MethodB and so on till ClassE.MethodE.
I need the processsors in ClassE which is 4 level inside the loop and don't want to pass that dictionary of processors from ClassA to ClassB and so on.
Please help!
I would use a Dictionary
which has a mapping between SeatType
and processing class. And in each iteration i take the correct processor from the Dictionary
.
E.g.
Dictionary<SteatType, IProcessor> processors = new Dictionary<SteatType, IProcessor>();
for (int i = 0; i < buses.Length; i++)
{
Bus b = buses[i];
IProcessor p = processors[b];
// p.process(b);
}
If you don't want to pass the processors
from class A
to class E
you can create a Helper
class which is a singleton and holds the processors
. So on each level you can call the singleton for the specific processor.
Or maybe when it is possible what i think looks quite better you inject the processors
in the constructor from the five classes A
to E
so it would even be possible to use different processor
Dictionaries
on different levels ;)