在實際項目中使用策略模式

1.首先定義一個接口

/**
 * @program: springboot
 * @description:
 * @author: Jhon_Li
 * @create: 2019-08-09 11:03
 **/
public interface AbstractDemo {
    public  String create();
    public TypeEnum type();
}

2.枚舉類


public enum TypeEnum {
    ONE(1),
    TWO(2);
    private int code;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    TypeEnum(int code) {
        this.code = code;
    }
}

3.實現類

@Component
public class JavaServiceImpl implements AbstractDemo {
    @Override
    public String create() {
        System.out.println("java");
        return "java";
    }

    @Override
    public TypeEnum type() {
        return TypeEnum.TWO;
    }
}
@Component
public class PythonServiceImpl implements AbstractDemo {
    @Override
    public String create() {
        System.out.println("python");
        return "python";
    }

    @Override
    public TypeEnum type() {
       return TypeEnum.ONE;
    }
}

4.具體的方法

@Component
public class Dispatcher {
    @Autowired
    private Map<String, AbstractDemo> eventSourceMap ;

    public String dispatch(TypeEnum typeEnum) {
        AbstractDemo eventSource = getEventSource(typeEnum);
        if (eventSource != null) {
            return eventSource.create();
        }
        return null;
    }

    private AbstractDemo getEventSource(TypeEnum typeEnum) {
        if (typeEnum == null || eventSourceMap == null || eventSourceMap.isEmpty()) {
            return null;
        }
        return eventSourceMap.values()
                .stream()
                .filter(eventSource -> typeEnum == eventSource.type())
                .findFirst()
                .orElse(null);
    }
}

5調用

 public static void main(String[] args) {
        Set<String> source = new HashSet<>();
        //配置class的名稱
        source.add(ApplicationConfiguration.class.getName());
        SpringApplication springApplication = new SpringApplication();
        springApplication.setSources(source);
        //  springApplication.setWebApplicationType(WebApplicationType.);
        ConfigurableApplicationContext context = springApplication.run(args);

      Dispatcher contextBean = context.getBean(Dispatcher.class);
        contextBean.dispatch(TypeEnum.TWO);
    }


    @SpringBootApplication
    public static class ApplicationConfiguration {


    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章