Reputation:
I have case which consists of three classes namely SourceFactory, Source, and SourceTypeI. I want to create instance of SourceTypeI only in SourceFactory. In other words, other than SourceFactory, no class can create instance of SourceTypeI. How can I prevent other classes can create SourceTypeI?
Expected usage;
SourceFactory sF = new SourceFactory();
Source source = sF.createSource();
// from there, I should reach methods of SourceTypeI via source
source.whoIs();
Classes
|-------------| |-----------------------|
|SourceTypeI | |SourceFactory |
|-------------| |-----------------------|
|+whoIs():void| |+createSource():Source |
| | | |
|-------------| |-----------------------|
|-----------------------------|
| Source | <- Source cannot be instantiated, it is used just a
|-----------------------------| for referencing instance of SourceTypeI
| |
|-----------------------------|
Upvotes: 4
Views: 626
Reputation: 31290
Sorry for changing the names.
public interface Restricted { // Source
public int getX();
}
public class Restrict { // SourceFactory
private class RestrictedImpl implements Restricted {
public int getX(){ return 42; }
}
public Restricted createRestricted(){
return new RestrictedImpl();
}
}
Restrict restrict = new Restrict();
Restricted restricted1 = restrict.createRestricted();
Upvotes: 1
Reputation: 201439
If I understand your question, you can put SourceFactory
and SourceTypeI
in the same package. Then make SourceTypeI
final. Next give SourceTypeI
package level (default) constructors.
SourceTypeI() { // <-- not public, not private, not protected.
super();
}
Then don't put "any other class(es)" in that package.
Upvotes: 1