如何防止其他类创建一个类的实例?

时间:2014-07-13 08:47:38

标签: java oop object-oriented-analysis

我的案例包括三个类,即SourceFactory,Source和SourceTypeI。我想在SourceFactory中创建SourceTypeI的实例。换句话说,除了SourceFactory之外,没有类可以创建SourceTypeI的实例。如何防止其他类可以创建SourceTypeI?

预期用途;

  SourceFactory sF = new SourceFactory();
  Source source = sF.createSource();

  // from there, I should reach methods of SourceTypeI via source
  source.whoIs();

  |-------------|           |-----------------------|
  |SourceTypeI  |           |SourceFactory          |
  |-------------|           |-----------------------|
  |+whoIs():void|           |+createSource():Source |
  |             |           |                       |
  |-------------|           |-----------------------|

  |-----------------------------|
  |    Source                   | <- Source cannot be instantiated, it is used just a 
  |-----------------------------|    for referencing instance of SourceTypeI 
  |                             |
  |-----------------------------|

2 个答案:

答案 0 :(得分:1)

如果我理解了您的问题,您可以将SourceFactorySourceTypeI放在同一个包中。然后让SourceTypeI最终。接下来给出SourceTypeI包级别(默认)构造函数。

SourceTypeI() { // <-- not public, not private, not protected.
  super();
}

然后不要在该包装中加入“任何其他类别”。

答案 1 :(得分:1)

很抱歉更改名称。

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