- Jul 29, 2005
- 521
- 1
- 81
So I have done quite a lot of programming over the years. This sounds terribly simple, but I believe it to be flawed in concept given the requirements. I am to create a base Comparator class with a single public method: public int Compare(Type item1, Type item2). This will return a basic 1, 0, -1 depending on how the items compare. There are different Comparison types, and here's the part that is messing with me, I am told to inherit the Comparator class into PriceComparator, CostComparator, etc. This would be fine if I was allowed to directly access the child object, but I am not allowed. I could create a new Comparator cmp = new PriceComparator(); and then access the Compare method in the child. But I'm not allowed to do this.
The goal is to have a single exposed Comparator class, with no knowledge of the children. I assume I need to instantiate a Comparator object and pass in my comparison type. So I would create: Comparator priceComparator = new Comparator("price"); Then I need to call priceComparator.Compare(item1, item2); Comparator would use the specified type (stored in the Comparator object) to decide what to do. But I can't simply call the child classes as this would result in infinitely calling constructors between parent and child until a stack exception occurred.
The real problem lies in what to do with the Compare() method. Since each child (i.e. PriceComparator) class has it own way of calculating comparisons, I have no idea how to get a simple:
Comparator priceComparator = new Comparator("price");
priceComparator .Compare(item1, item2);
to work properly. Can anyone offer some pointers? (no pun intended)
Thanks!
The goal is to have a single exposed Comparator class, with no knowledge of the children. I assume I need to instantiate a Comparator object and pass in my comparison type. So I would create: Comparator priceComparator = new Comparator("price"); Then I need to call priceComparator.Compare(item1, item2); Comparator would use the specified type (stored in the Comparator object) to decide what to do. But I can't simply call the child classes as this would result in infinitely calling constructors between parent and child until a stack exception occurred.
The real problem lies in what to do with the Compare() method. Since each child (i.e. PriceComparator) class has it own way of calculating comparisons, I have no idea how to get a simple:
Comparator priceComparator = new Comparator("price");
priceComparator .Compare(item1, item2);
to work properly. Can anyone offer some pointers? (no pun intended)
Thanks!
