Atom Feed SITE FEED   ADD TO GOOGLE READER

My private interfaces design pattern

So I found myself writing some code that seemed like a GoF design pattern. I'm not so sure that it is, but if it were, here's its criteria...

Name: Private Interfaces
Intent: Implement methods in a class without exposing them in the public API.
Motivation: Hiding methods prevents them from being called by the API's user. Method hiding also streamlines the API of a class. For example, a class may need to receive mouse events without exposing methods like mouseClicked() in its external API.
Applicability: When the class must implement an API without exposing it.
Consequences: Essentially, Interface methods become 'private'. This prevents extending classes from overriding them and users from calling them. The interface may still be exposed where it is needed.
Implementation: Add an inner class that implements all the private interfaces. Create a private member of this inner class, and use pass as the parameter wherever the private interfaces are needed.
Sample Code:
/** Before. This class exposes 6 methods */

public class ClickCounter implements MouseListener {
private int clicks = 0;
private int presses = 0;
private int releases = 0;
public MyClass(Component c) {
c.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) { clicks++; }
public void mousePressed(MouseEvent e) { presses++; }
public void mouseReleased(MouseEvent e) { released++; }
public int getClickCount() { return clicks; }
public int getPressCount() { return presses; }
public int getReleaseCount() { return releases; }
}

/** After. This class exposes only 3 methods */

public class ClickCounter {
private int clicks = 0;
private int presses = 0;
private int releases = 0;
private PrivateInterfaces privateInterfaces = new PrivateInterfaces();
public MyClass(Component c) {
c.addMouseListener(privateInterfaces);
}
private class PrivateInterfaces implements MouseListener {
public void mouseClicked(MouseEvent e) { clicks++; }
public void mousePressed(MouseEvent e) { presses++; }
public void mouseReleased(MouseEvent e) { released++; }
}
public int getClickCount() { return clicks; }
public int getPressCount() { return presses; }
public int getReleaseCount() { return releases; }
}

Related Patterns: Event listener