i have factory object challengemanager
generate instances of challenge
object game i'm building. there many challenges. constructors each challenge
class derivation different, there common interface among them, defined in base class.
when call manager.createchallenge()
, returns instance of challenge
, 1 of derived types.
ideally, keep code object construction inside derived class itself, code related object co-located. example:
class challenge {} class challengea : challenge { public static challenge makechallenge() { return new challengea(); } } class challengeb : challenge { public static challenge makechallenge() { return new challengeb(); } }
now, challengemanager.createchallenge()
call needs decide class call makechallenge()
on. implementation of construction contained class itself.
using paradigm, every derived class must define static makechallenge()
method. however, since method static one, not able make use of interface here, requiring it.
it's not big deal, since can remember add correct method signature each derived class. however, wondering if there more elegant design should consider.
i pattern describing , use often. way is:
abstract class challenge { private challenge() {} private class challengea : challenge { public challengea() { ... } } private class challengeb : challenge { public challengeb() { ... } } public static challenge makea() { return new challengea(); } public static challenge makeb() { return new challengeb(); } }
this pattern has many nice properties. no 1 can make new challenge
because abstract. no 1 can make derived class because challenge
's default ctor private. no 1 can @ challengea
or challengeb
because private. define interface challenge
, interface client needs understand.
when client wants a
, ask challenge
one, , it. don't need worry fact behind scenes, a
implemented challengea
. challenge
can use.