On a project I was working on, there was a requirement to encapsulate the implementations in such a way that consumers of the API were forced to program to interfaces rather than implementations. This is a fairly common requirement, and one that is commonly solved in Java using default access rather than public implementations, and public factories to instantiate these.
This has some disadvantages however, namely that you either end up with a number of identical factories, only distinguished by what implementation it instantiates, and the package it’s living in.
I created a generic factory which instantiates classes using reflection, and then casting the instance to the interface specified. The salient feature looks much like this – Where implementation Name is the fully qualified class name of the implementation and interfaze is the interface which we want to return the object as.
var implementation : * = getDefinitionByName(implementationName); return interfaze(new implementation());
This will then create an instance of the implementation which we can then use parsley to inject in the appropriate places. This leaves us with the issue that a dev unaware of the pattern could instantiate the implementation directly. There is an easy fix to this. Simply create a custom namespace:
package some.package.namespaces
{
public namespace OUR_Namespace_Internal
{
}
}
and add the following line prior to the class definition of your implementation:
use namespace OUR_Namespace_Internal;
[ExcludeClass]
public class SomeClass implements SomeInterface {
The net result? An implementation that cannot be instantiated unless the consumer explicitely uses our new namespace, and a factory enforcing interface use.