方案1:@Autowired Map
public interface ClientService {void hanlde(Object obj);String type();
}
@Service
public class PcClientService implements ClientService { @Overridepublic void handle(Object obj) {// todo pc客户端逻辑} @Overridepublic String type() {// 使用时根据type匹配对应实现类,可以使用枚举或常量代替return "pcClientService ";}
}
@Service
public class AndroidClientService implements ClientService { @Overridepublic void handle(Object obj) {// todo Android客户端逻辑} @Overridepublic String type() {// 使用时根据type匹配对应实现类(对应beanname),可以使用枚举或常量代替return "androidClientService ";}
}
@Autowiredprivate Map<String, ClientService> clientHandlers;// 策略调用public void strategy(String strategyType) {clientHandlers.get(strategyType).handle();}
方案2: @PostConstruct
public interface ClientService {void hanlde(Object obj);
}
public class ClientManager {private static final Map<String, ClientService> clientHandlers = new ConcurrentHashMap<>();public static void register(String type, ClientService service) {clientHandlers.put(type, service);}
}
@Component
public class PcClientServiceImpl implements ClientService{@PostConstructpublic void afterInit() {// 不需要 type() 方法了// 但我们仍需要在注册策略时提供 type 参数ClientManager.register("pcClientServiceImpl ", this);}// 使用方式同上
}
方案三:InitializingBean
相比第二种@PostConstruct增加了约束力,避免忘记实现@PostConstruct方法
public interface ClientService extends InitializingBean {void hanlde(Object obj);
}
public class PcClientServiceImpl implements ClientService {@Overridepublic void hanlde(Object obj) {// todo 业务逻辑}@Overridepublic void afterPropertiesSet() throws Exception { ClientManager.register("pcClientServiceImpl ", this);}
}
使用时就根据不同type,调用不同策略算法