简体   繁体   中英

How to prevent other classes to create instance of one class?

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 
  |                             |
  |-----------------------------|

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM