I have a factory ChallengeManager object to generate instances of the Challenge object for the game I am creating. There are a lot of problems. The constructors for each output of the Challenge class are different, but there is a common interface between them defined in the base class.
When I call manager.CreateChallenge() , it returns an instance of Challenge , which is one of the derived types.
Ideally, I would like to save the code for building the object inside the derived class itself, so all the code associated with this object is located together. Example:
class Challenge {} class ChallengeA : Challenge { public static Challenge MakeChallenge() { return new ChallengeA(); } } class ChallengeB : Challenge { public static Challenge MakeChallenge() { return new ChallengeB(); } }
Now my ChallengeManager.CreateChallenge() call should only be solved by the class to call MakeChallenge() on. The implementation of the construction is contained in the class itself.
Using this paradigm, each derived class must define a static MakeChallenge() method. However, since the method is static, I cannot use the interface here, requiring it.
This is not a big deal, as I can easily add the correct method signature for each derived class. However, I am wondering if there is a more elegant design that I should consider.
c # design-patterns factory-pattern
gdbj
source share