vendredi 13 novembre 2015

Java +Strategy + Factory + same package = how to hide specialized classes?

I want to hide the specialization classes from the external classes of the same package.

Example:

package com.app.letter;
public interface LetterChange {
   void change();
}

public class A implements LetterChange{
   public void change(){..}
}

public class B implements LetterChange{
   public void change(){..}
}

To instantiate these classes I use a factory....

package com.app.letter;
public class LetterFactory{
   public static LetterChange getInstance(Object doesNotMatter){
   return doesNotMatter.isA() ? new A() : new B();
}

Note, all of them are in the same package and I DO NOT WANT to put the factory and the specialized classes in a sub package and change the specialization classes' constructors to default (package).

Following this example, I have a third class in the same package

package com.app.letter;

public class DoesNotMatterClass{
   public void situations(){       
      LetterFactory.getInstance(null); // Legal
      new A(); Illegal
      new B(); Illegal    
   }
}

I want to provide the A or B only by the factory LetterFactory.getInstance(doesNotMatter) which is in the same package.

Aucun commentaire:

Enregistrer un commentaire