I have an abstract class AxisState
with two concrete subclasses XState
and YState
. They're supposed to be immutable objects with a bunch of methods that return a different AxisState
. Most of these methods are completely defined in AxisState
, and a few of them are abstract and implemented in the concrete subclasses.
The problem is that I need to somehow return a new instance of the current concrete subtype of AxisState
from within the methods entirely implemented in AxisState
.
What I'm currently doing is implementing a method abstract AxisState NewStateOfSameType()
which is implemented as returning a new XState
or YState
from within these subtypes, respectively.
public abstract class AxisState {
public abstract AxisState NewStateOfSameType(/*...*/);
public abstract AxisState OverloadMethod();
public abstract AxisState AnotherOverloadMethod();
public AxisState(int fieldOne, int fieldTwo) {
// ...
}
public AxisState NextState(/*...*/) {
// ...
return NewStateOfSameType(fieldOne, fieldTwo);
}
// ...
}
And the implementation in XState
/YState
:
public class XState : AxisState {
public XState(int fieldOne, int fieldTwo) : base(fieldOne, fieldTwo) {}
public override AxisState NewStateOfSameType(int fieldOne, int fieldTwo) {
return new XState(fieldOne, fieldTwo);
}
// Abstract methods implemented here
}
public class YState : AxisState {
public YState(int fieldOne, int fieldTwo) : base(fieldOne, fieldTwo) {}
public override AxisState NewStateOfSameType(int fieldOne, int fieldTwo) {
return new YState(fieldOne, fieldTwo);
}
// Abstract methods implemented here
}
Is there a cleaner way to handle all this, or some way to restructure this whole thing?