我遇到了类似的问题要解决,我真正做的是,它可能会有所帮助。
像定义任务枚举。
public enum Tasks {
Task1(SubTasks.values());
Tasks(PagesEnumI[] pages) {
this.pages = pages;
}
PagesEnumI[] pages;
// define setter and getter
}
定义的子任务,如
public interface PagesEnumI {
String getName();
String getUrl();
}
public enum SubTasks implements PagesEnumI {
Home("home_url");
SubTasks(String url) {
this.url = url;
}
private String url;
@Override
public String getUrl() {
return url;
}
@Override
public String getName() {
return this.name();
}
}
定义服务以调用每个子任务枚举,例如
public interface PageI {
void process();
Sites getTaskName();
PagesEnumI getSubTaskName();
}
@Component
public class Home implements PageI {
// function per SubTask to process
@Override
public void process() {}
// to get the information about Main Task
@Override
public Tasks getTaskName() {
return Tasks.Task1;
}
// to get the information about Sub Task
@Override
public PagesEnumI getSubTaskName() {
return Task1.Home;
}
}
定义一个工厂,如...
@Component
public class PageFactory {
Set<PageI> pages;
// HashMap for keeping objects into
private static HashMap<String, PageI> pagesFactory = new HashMap<>();
@Autowired
public void setPages(Set<PageI> pages) {
this.pages = pages;
}
// construct key by
private static String constructKey(Tasks taks, PagesEnumI page) {
return task.name() + "__" + page.getName();
}
// PostConstruct means after construct class object this method should get run
// iterating over all pages and storing into Map
@PostConstruct
private void postConstruct() {
for (PageI pageI : pages) {
pagesFactory.put(constructKey(pageI.getTaskName(), pageI.getSubTaskName()), pageI);
}
}
// getting object from factory
public PageI getPageObject(Tasks task, PagesEnumI page) {
return pagesFactory.get(constructKey(task, page));
}
}
到目前为止,我们已经注册了我们的枚举(Tasks 和 SunTasks)及其服务(使用 Tasks 和 SubTasks 的 getter),现在定义一个工厂来调用服务process
方法。
@SpringBootApplication
public class Application implements CommandLineRunner {
PageFactory factory;
@Autowired
public void setFactory(PageFactory factory) {
this.factory = factory;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
// for each task we might have different sub task
Arrays.stream(Tasks.values()).forEach(
task -> {
// for each and subtask of a task need to perform process
for (PagesEnumI page : task.getPages()) {
PageI pageI = factory.getPageObject(task, page);
pageI.process();
}
}
);
}
}
这不是完全相似的问题,解决它的方法可能相似。所以我认为把它放在这里可能会有所帮助。请不要通过命名,只是试图理解概念。如果有人有更多的投入,请分享。