看一下这个例子:
class Parent{ Child child = new Child(); Random r = new Random(); } class Child{ public Child(){ //access a method from Random r from here without creating a new Random() } }
如何从子对象中访问随机对象?
让Parent类将自己的实例传递Random给Child该类。
Parent
Random
Child
class Parent{ Child child; Random r = new Random(); public Parent() { child = new Child(r); } } class Child{ public Child(Random r){ } }
经典Occam剃刀。