Example

A sample implementation of this pattern is available in the folder 09-module-patterns/01-seperate-interface-impl. The module pattern.one has the interface PublicInterface exposed in the pattern.one.external package, while the implementation classes PrivateImplA and PrivateImplB are in the encapsulated pattern.one.internal package:

    module pattern.one { 
      exports pattern.one.external; 
    } 

We'd like the consuming modules to access the private instances through the public interface type. To facilitate this, there's a factory class Factory exposed by the module. This class has a public method getApiInstance that takes in an argument and then based on the value, returns the right implementation class. In the sample code, there's a simple boolean flag that affects whether one implementation instance is returned over another, but in a real-world module, this selection criteria would be more meaningful to what's returned, as this is how the consumer picks the right API instance based on their requirements. The return type of the factory method is an instance of the public interface. Thus, the consumer module doesn't know about the implementation details:

    public class Factory { 
      public PublicInterface getApiInstance(boolean selector) { 
        if (selector) { 
          return new PrivateImplA(); 
        } 
        return new PrivateImplB(); 
      } 
    } 

Benefits:

  • Hides the details from the consumer so that they don't have to know the internals
  • Allows you to change the implementation or add new implementation types without the consumers having to change the way they interact with the module
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.25