We have
Initializable interface: which is where initialization happen,
public interface Initializable { public void init(); public boolean initialized(); public boolean isLazyInit(); public void setInited(boolean status); public String getName(); }InitializationDirector : which does the initialization of required object,
public class InitializationManager { public static void initialize(String module){ for(Initializable registered:InitializableRegistry.getInits()){ if(registered.name().equalsIgnoreCase(module)) initialize(registered); } } public static void initAll(){ for(Initializable registered:InitializableRegistry.getInits()){ initialize(registered); } } public static void initialize(Initializable initializable){ if(!initializable.initialized()){ initializable.init(); initializable.setInited(true); } } }
InitializableRegistry : registry of all initializables
public class InitializableRegistry { private static List<Initializable> initializables=new ArrayList<Initializable>(5); public static void registerInitializable(Initializable init){ if(!init.isLazyInit()){ System.out.println("initializing "+init.name()+" on registeration"); init.init(); init.setInited(true); } initializables.add(init); } public static List<Initializable> getInits(){ return initializables; } }Test,
public class LazyInitDemo { public static void main(String[] args) { InitializableRegistry.registerInitializable(new EngineCheck()); InitializableRegistry.registerInitializable(new EmergencySetups()); InitializableRegistry.registerInitializable(new AutoPilot()); InitializableRegistry.registerInitializable(new FlightPath()); System.out.println("---lazy init on demand of particular module"); InitializationManager.initialize("FlightPath"); System.out.println("---init whatever is left"); InitializationManager.initAll(); } }sample output
initializing EngineCheck on registeration initing Engine check initializing Emergency on registeration initing emergency modules ---lazy init on demand of particular module initing FlightPath module ---init whatever is left initing AutoPiloting
No comments:
Post a Comment