This is a common design in the enterprise Java level (though, most of the time references get injected by some frameworks/libraries):
I have an interface
import java.util.*;
public interface ProductRepository {
public List <Product> getAllProducts();
}
And its implementation
public class ProductRepositoryImp implements ProductRepository {
private List<Product> products = new ArrayList<Product>();
public ProductRepositoryImp() {
products.add(new Product("Blackberry", 24000));
products.add(new Product("Nokia", 45000));
products.add(new Product("Samsung", 91000));
}
@Override
public List<Product> getAllProducts() {
return this.products;
}
public int localMethod(){
return 2;
}
}
In the main class (controller) I reference the interface (ProductRepository
) instead of the implementation (ProductRepositoryImp
)
public class ProductController {
static ProductRepository productRepository;
public static void main(String[] args) {
productRepository = new ProductRepositoryImp();
for (Product p : productRepository.getAllProducts()) {
System.out.println(p.getName());
System.out.println(p.getPrice());
System.out.println("");
} } }
Why?
Here is an explanation I read in a book:
It is not the best practice to connect two layers (controller and persistence) with a direct reference. Instead, we can, in future, have an interface reference in the controller so that we can easily switch to different implementations of the repository without doing any code changes in the controller class.
What's the benefit of accessing .getAllProducts()
from the ProductRepository
instance instead of an instance of ProductRepositoryImp
?
What's the point of "without doing any code changes" switching in the quote above? I know it's something related if we have
lets say "AnotherProductRepositoryImp
"?.
What if I want to heavily access some .localMethod()
instead which is inside the ProductRepositoryImp
instance ?