TWi*_*Rob 2 java class inner-classes
我有以下结构:
public class Outer {
public /*non-static*/ final class Inner {
// to prevent instantiating other than in method `create`
private Inner(/* ... */) { /* ... */ }
/* ... */
}
Inner create(/* ... */) {
return new Inner(/* ... */);
}
void operateOn(Inner inner) {
// TODO check if inner for this Outer instance
}
}
Run Code Online (Sandbox Code Playgroud)
和这样的用法:
Outer manager = new Outer();
Inner state = manager.create(/* ... */);
Run Code Online (Sandbox Code Playgroud)
和其他地方
manager.operateOn(state);
Run Code Online (Sandbox Code Playgroud)
我想创建一个防呆的实用程序类,意味着Outer.operateOn
只接受Inner
自己拥有的实例
我知道所有非静态内部类都通过Outer.this
其类体内部引用(所有)外部类.
我想知道是否有更好的方法来检查这个,而不是添加任何方法来Inner
喜欢isOwnedBy(Outer outer) { return outer == Outer.this; }
或getOwner() { return Outer.this }
.
我想创建一个万无一失的....
这总比你想象的要难.
manager.operateOn(状态);
如果你知道它与该州的经理有关,我就不会提供经理.
试试吧
state.operate();
Run Code Online (Sandbox Code Playgroud)
该state
知道哪些manager
应该使用.这样就无法指定错误的管理器,因为您无法更改管理器.