所以我们有这个课class Identity
,还有一个class CanineCommunication
那么如果我们想定义一个类
class Dog {
public Dog() {
Identity id;
CanineCommunication cc;
}
id.getParticulars(); //we can call all the public Identity methods
cc.getMoves(); //and also the public CanineCommunication methods
}
但是,假设CanineCommunication类中的方法需要使用Identity方法-一种显而易见的方法是:
class CanineCommunication {
getNoises(Identity id) {
id.getParticulars();
//~~if small be squeaky &c~~
}
另一种方法是:
class CanineCommunication {
Identity id;
public canineCommunication (Identity id) {
this.id=id;
}
getNoises() {
id.getParticulars();
//~~if small be squeaky &c~~
}
这些方法如何比较?还有其他(更好/更差)的方法来实现这一目标吗?
这取决于您的设计:在将Identity对象传递给构造函数的情况下,您正在使用Identity的单个实例,并且可能需要照顾任何静态变量或威胁不安全的变量
如果您每次都传递身份对象,则与上述情况类似,如果您传递相同的对象,但是您可以灵活地每次传递新对象
或多或少取决于您的要求
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句