java策略模式三种实现方案

方案1:@Autowired Map

public interface ClientService {
    void hanlde(Object obj);
    String type();
}
@Service
public class PcClientService implements ClientService  {    
    @Override
    public void handle(Object obj) {
        // todo pc客户端逻辑
    }    
    @Override
    public String type() {
        // 使用时根据type匹配对应实现类,可以使用枚举或常量代替
        return "pcClientService ";
    }
}
@Service
public class AndroidClientService implements ClientService  {    
    @Override
    public void handle(Object obj) {
        // todo Android客户端逻辑
    }    
    @Override
    public String type() {
        // 使用时根据type匹配对应实现类(对应beanname),可以使用枚举或常量代替
        return "androidClientService ";
    }
}
    @Autowired
    private 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{
    @PostConstruct
    public 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 {
    @Override
    public void hanlde(Object obj) {
    	// todo 业务逻辑
    }
    @Override
    public void afterPropertiesSet() throws Exception {    
        ClientManager.register("pcClientServiceImpl ", this);
    }
}

使用时就根据不同type,调用不同策略算法

你可能感兴趣的:(学习,java,策略模式,python)