Reputation: 10068
I have an object with two different constructors:
public class MyClass {
public MyClass(arg1, arg2) {
//constructor
}
public MyClass() {};
}
I need to invoke the second one only by a specific class of my software (the first one could be invoked anywhere). Is there a design pattern specific for this case?
MyClass
and the invoking class are in two different packages, so a package-private constructor is not a solution.
Upvotes: 1
Views: 135
Reputation: 54692
Without design pattern it can be done in one way. Set one constructor public, which will be invoked from all class. And the other declare it package private. Now place this class and the specific on in the same package.
public class MyClass {
public MyClass(arg1, arg2) {
//constructor
}
MyClass() {}; // only for the class in the same package
}
So now the public constructor can be used from all while the package protected constructor can be invoked only by the class in the same package.
Another Option
You can use a different implementaion of factory pattern
public class MyClass {
public MyClass(arg1, arg2) {
//constructor
}
public MyClass() {};
}
And the factory
public class MyClassFactory{
public static MyClass createMyClass(Object o){
if (o instanceOf SpecificClass)
return new MyClass();
else
return new MyClass(arg1,arg2);
}
}
Now call like
MyClass mC = MyclassFactory.createMyClass(this);
N.B.. I just ommitted the arguments. You can pass the arguments in createMyClass
method.
Upvotes: 3
Reputation: 9609
You can do something like this.
public class Test {
public Test() {
StackTraceElement[] stack = new Throwable().getStackTrace();
StackTraceElement topOfStack = stack[0];
if (!topOfStack.getClassName().equals("mypackage.MyClass"))
throw new SecurityException("Haha! You are not allowed to call me!");
// ....
}
public static void main(String[] args) {
new Test(); // Haha! You are not allowed to call me!
}
}
Upvotes: 1