本文主要是介绍代码优化之工厂,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 定义抽象类
public interface PullDataService{void pullData();
}
- 定义各自得类型并实现该接口
@Service("note")
public class NoteService implements PullDataService{@Overridepublic void pullData(){System.out.println("node");}
}
@Service("order")
public class OrderService implements PullDataService{@Overridepublic void pullData(){System.out.println("order");}
}
- 项目启动生成工厂
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;import java.util.HashMap;
import java.util.Map;@Component
@RequiredArgsConstructor
public class ServiceFactory implements ApplicationRunner{public static final Map<String,PullDataService> SERVICE_MAP =new HashMap<>();private final ApplicationContext applicationContext;@Overridepublic void run(ApplicationArguments args){Map<String, PullDataService> beansOfType = applicationContext.getBeansOfType(JkyService.class);beansOfType.forEach(SERVICE_MAP::put);}public PullDataService getService(String serviceName){return SERVICE_MAP.get(serviceName);}
}
- 使用
private final ServiceFactory serviceFactory;@GetMapping("/x")@ApiOperation(value = "x")public void x(@RequestParam("service")String service){serviceFactory.getService(service).pullData();}
这篇关于代码优化之工厂的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!