È possibile creare una classe astratta che definisce il comportamento predefinito per le richieste comuni e utilizza il tipo generico. In java:
public abstract class AbstractRepository<T> {
...
//When constructed pass additional details if needed
public AbstractRepository(Class<T> type, String baseURL, Client client) {
this.type = type;
this.baseURL = baseURL;
this.client = client;
}
public T findById(final String id) {
//This is where you actually make the call and if you need to
//provide the object type information to whatever means you are
//using to deserialize the return
return client.get(id, ...);
}
public List<T> findAll() {
return client.get(...);
}
public T update(final T obj) {
return client.update(obj, ...);
}
public List<T> findAllByTerms(SearchTerms searchTerms) {
return client.get(formatSearchTerms(searchTerms),...);
}
...
}
Quindi estendi questa classe con i tuoi tipi
public class OrderRepository extends AbstractRepository<Order> {
//Call super constructor, pass values if needed
public OrderRepository(Client client) {
super(Order.class, Order.BASE_URL, client);
}
//If you need 'special' searches for Order, add them in
public Integer getTotalOrderCount() {
return super.findAll().size();
}
public List<Order> findAllByOrderType() {
SearchTerms searchTerms = new SearchTerms();
searchTerms.add("type", OrderTypes.OVERSEAS);
return super.finalAllByTerms(searchTerms);
}
}
Quindi se vuoi che una classe client in cui tutte le chiamate siano avviate puoi farlo in alcuni modi, il mio modo ingenuo sarebbe di contenere tutti i tuoi repository e i loro metodi sarebbero proxy per loro:
public class ApiClient {
private OrderRepository orderRepository;
private OrderItemRepository orderItemRepository;
public ApiClient() {
//Just an holder
Client client = new Client("user", "password");
this.orderRepository = new OrderRepository(client);
this.orderItemRepository = new OrderItemRepository(client);
}
public Order findOrderById(Itneger id) {
return orderRepository.findById(id);
}
public List<Order> findAllOrders() {
return orderRepository.findAll();
}
public OrderItem findOrderItemById(Integer id) {
return orderItemRepository.findById(id);
}
...
}