Home > Java, Programming > Only expose API Methods to users

Only expose API Methods to users

May 21st, 2010 jmguilla

This post is also available in: French

Accessor Pattern

Everybody has always been considered by separation of code i.e, related functionalities written in the same packages for instance. The issue that comes up when writing an API is that you likely need to call some of that methods in other packages but you still don’t want to expose them to users. In Java language you can use 4 differents modifiers: Public, Protected, Package and Private. To answer our problem it lacks a modifier, let’s name it “Friendly”, that would allow to call methods in other packages under friendship. That would solve both both code separation concerns and non exposable methods. Here is an example of the Accessor Pattern:

package jean.michel.guillaume.api;
 
/**
 * class part of the public API, every one can use it
 */
public final class RMCore {
    static {
        Accessor.setDefault(new AccessorImpl());
    }
 
    /** Anyone can change value of the item. */
    public void addNode(String url) {
        //impl
    }
 
    /** Only friends can notify node changes.  */
    void notifyNodeUpdate(String url) {
        //impl
    }
}
package jean.michel.guillaume;
 
/**
 * We'll use this class to expose methods in separate packages
 */
public abstract class Accessor {
    private static volatile Accessor DEFAULT;
    public static Accessor getDefault(){
        Accessor a = DEFAULT;
        if( a != null){
            return a;
        }
        try{
            Class.forName(RMCore.class.getName(), true, RMCore.class.getClassLoader());
        }catch(Exception e){
            e.printStackTrace();
        }
        return DEFAULT;
    }
 
    public static void setDefault(Accessor a){
        if( DEFAULT != null){
            throw new IllegalStateException();
        }
        DEFAULT = a;
    }
 
    protected abstract void void notifyNodeUpdate(String url);
}
package jean.michel.guillaume.api;
 
import jean.michel.guillaume.Accessor;
 
/**
 * Now, we can just implement our own Accessor in a separate package
 * to gain access to friendly methods!! Don't forget to declare AccessorImpl
 * package private!!
 */
final class AccessorImpl extends Accessor {
 
    protected void notifyNodeUpate(String url) {
 
    }
}
Categories: Java, Programming Tags: ,
  1. No comments yet.
  1. October 23rd, 2014 at 23:23 | #1
Comments are closed.