Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delegate instantiation of constructor by classtype?

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...

like image 559
membersound Avatar asked Feb 11 '23 12:02

membersound


1 Answers

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);
    }
}
like image 193
Holger Avatar answered Feb 13 '23 04:02

Holger