I want to write a Java class that wraps another class in a specific way for a multi-tenant system:
Example:
Take this existing class:
MyService{
public List<Product> getProducts(Account filterWithUseraccount);
public List<Purchase> getPurchases(Account filterWithUseraccount, Date fromDate, Date tillDate);
public List<Category> getCategories(Account filterWithUseraccount, Category parentCategory);
}
And I want to create this new class, but the methods should be "auto-generated":
MyTenantOrientedService{
// Assign an account which will be used to call all MyService methods
private Account filterWithUseraccount;
// The service being wrapped
private MyService myService;
public List<Product> getProducts(){
return myService.getProducts(filterWithUseraccount);
}
public List<Purchase> getPurchases(Date fromDate, Date tillDate){
return myService.getPurchases(filterWithUseraccount, fromDate, tillDate);
}
public List<Category> getCategories(Category parentCategory){
return myService.getCategories(filterWithUseraccount, parentCategory);
}
}
As you can see, the methods in MyTenantOrientedService are the same as in MyService, except that the parameter "Account filterWithUseraccount" is never used and can be taken from the private property.
This is a simple example, but imagine a class with a lot of methods, making it a huge chore to create the wrapping functions. This is a lot of code duplication and bug can easily be created.
I believe a solution might exist using AOP or other design pattern, but I can't figure out which.
Your IDE handles this kind of tasks for you.
For example, you could add a member variabile of type MyService inside MyTenantOrientedService and, on Eclipse, right-click on MyTenantOrientedService, then click on "Source -> Generate Delegate Methods"
It is applying the Delegation Pattern for you.