For design of an API in java, I came up with following pattern to fulfill certain requirements which are listed here
- actual public API class should be implemented as a final class, to prevent inheritance and possible misuses
- actual public API class should not expose anything more than required methods.
- separation of API classes and internal implementation into different packages
- scope for extensibility or evolution in both public and internal classes
the sample code is as follows:
package external;
import internal.AbstractProduct;
public final class Product extends AbstractProduct{
protected Product(int a, int b){
super(a,b);
}
@Override
public int result(){
return super.result();
}
}
public class ProductFactory {
public static Product createProudct(int a, int b){
return new Product(a, b);
}
}
and internal classes are as follows:
package internal;
public abstract class AbstractProduct {
private final AbstractProduct impl;
protected AbstractProduct(int a, int b){
impl = new ProductImpl(a, b);
}
protected AbstractProduct(){
impl = null;
}
protected int result(){
return impl.result();
}
}
class ProductImpl extends AbstractProduct{
private int a;
private int b;
ProductImpl(int a, int b){
this.a = a;
this.b = b;
}
@Override
protected int result(){
return a*b;
}
}
Although it works fine and also has appropriate access levels, but I only have beginner level skills with design patterns or API design, so it seems difficult for me to spot possible glitches with this. So are there any problems with this Or is it some already practiced pattern?