How to delegate an instance of classtype constructor?

I have several classes that extend BaseClass. Now I want to define the active class statically in DelegatorContext, and each object creation should be based on an 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 will have an even larger template if additional extension objects are introduced BaseClass.

Is there a better sample for my problem? Maybe even with Java8 and Functions? Or generics?

I use this construct to switch implementation at runtime ...

+4
source share
3 answers

I think 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;

, , factory ( )

factory, :

class Delegator {
    BaseClass create(String firstname, String lastname) {
        return DelegatorContext.active.create(firstname, lastname);
    }
}
+3

DelegatorContext generic , BaseClass.

, activeClass static, Class<T> Class activeClass.

:

class DelegatorContext<T extends BaseClass> {
    private Class<T> clazz;

    public T activeClass;

    private DelegatorContext(Class<T> clazz) { 
         this.clazz = clazz;
    }

    public T createInstance(String firstname, String secondname) {
        activeClass = clazz.newInstance();
        activeClass.setFirstName(firstname);
        activeClass.setSecondName(secondname);
        return activeClass;
    }

    public static <T extends BaseClass> DelegatorContext<T> of(Class<T> clazz) {
        return new DelegatorContext<T>(clazz);
    }
}

:

<T extends BaseClass> T create(Class<T> clazz, String firstname, String lastname) {
    return DelegatorContext.of(clazz).createInstance(firstname, lastname);
}
+3

, , :

enum DelegatorContext {
    First {
        @Override
        BaseClass instantiate(String firstName, String lastName) {
            return new FirstClass(firstName, lastName);
        }
    },
    Second{
        @Override
        BaseClass instantiate(String firstName, String lastName) {
            return new SecondClass(firstName, lastName);
        }
    };

    static Context defaultContext;
    abstract BaseClass instantiate(String firstName, String lastName);
}
+2

All Articles