Skip to Content
I staggered over a quite common problem: I had a set of interfaces and a factory providing implementations in a “public” package. I wished to separate the implementation into a different package as there were different possible implementations intended. For that reason I could not make all the implmentation classes package-private as the factory had to access at least one implmentation class providing the concrete instances. So I poked around a bit how to prevent direct instantiation of the accessor class in the implementation package. I came up with the solution presented here. First of all there is an interface in an api package.
package org.birenheide.api;      

public interface IApi {          
  public void doIt();  
}

 

Then I want to have a factory producing an instance:
package org.birenheide.api;  
import org.birenheide.impl.ApiImpl;  

public final class InterfaceFactory {   

  public static IApi newImplementation() {         
    return new ApiImpl();     
  }        

  private InterfaceFactory() {}  
}
and an implementation in a different package:
package org.birenheide.impl;  

import org.birenheide.api.IApi;  

public class ApiImpl implements IApi {
  public ApiImpl() {}        
  public void doIt() {     
    //Do something here     
  } 
}
Not very secure though… I do not want to instantiate anyone ApiImpl on his own. So I pass an instance of the factory into it which nobody can instantiate:
package org.birenheide.impl;  

import org.birenheide.api.IApi; 
import org.birenheide.api.InterfaceFactory;  

public class ApiImpl implements IApi {       
  
  public ApiImpl(InterfaceFactory factory) {         
    if (factory == null) {             
      throw new IllegalArgumentException();         
    }     
  }      
  
  public void doIt() {  
  } 
}
and change the factory to:
package org.birenheide.api;  

import org.birenheide.impl.ApiImpl;  

public final class InterfaceFactory {       

  private static InterfaceFactory securingInstance = new InterfaceFactory();        
  
  public static IApi newImplementation() {         
    return new ApiImpl(securingInstance);     
  }        

  private InterfaceFactory() {} 
}
Of course this gives no hard guarantee and can be broken by means of reflection. But at least it makes very clear that I do not want anybody instantiating the implementation.
To report this post you need to login first.

1 Comment

You must be Logged on to comment or reply to a post.

  1. Oliver Kohl
    Hi Richard,

    thanks for the nice blog and the interesting approach to secure class instantiation. Haven’t seen that before.

    I’m really interested in patterns, so if you have more of that stuff please keep on blogging!

    Thanks,
      ok

    (0) 

Leave a Reply