I have several classes that extend a BaseClass
. Now I want to define an active class statically in a DelegatorContext
, and each object creation should be based on the active context.
Example:
class BaseClass {
String firstname, lastname;
}
class FirstClas extends BaseClass {}
class SndClass extends BaseClass {}
class DelegatorContext {
public static BaseClass activeClass;
}
class Delegator {
BaseClass create(String firstname, String lastname) {
return DelegatorContext.activeClass instanceof FirstClass
? new FirstClass(firstname, lastname) : new SndClass(firstname, lastname);
}
}
The example would get even more boilerplate if more entities are introduced extending BaseClass
.
Is there a better pattern for my kind of problem? Maybe even with Java8 and Functions
? Or Generics?
I'm using this construct for beeing able to switch the implementation at runtime...
I guess, you mean something like this:
interface BaseClassFactory {
BaseClass create(String firstname, String lastname);
}
class DelegatorContext {
public static BaseClassFactory active;
}
…
DelegatorContext.active=FirstClass::new;
…
DelegatorContext.active=SndClass::new;
which requires that all subclasses have a constructor with the same signature, matching the signature of the factory interface (and interestingly gives an example to this recent question)
You don’t really need the other factory class but for completeness, it would be:
class Delegator {
BaseClass create(String firstname, String lastname) {
return DelegatorContext.active.create(firstname, lastname);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With