考虑以下情况:
我为嵌入式(调制解调器)设备编写了一个 java 程序。SDK 不提供 Cloneable。因此我有class GsmSignalStrength
方法clone()
,但它不是来自Object.clone()
,它是“我的”实现。我想知道这是否有用且正确,或者我应该GsmSignalStrength
在评论中使用复制构造函数吗?我看不到复制构造函数的优势,因为我必须在我的 StateMachine 中创建另一个 GsmSignalStrength 对象。
这是我的代码...
文件 1“Status.java”:
class Status
{
Status(GsmSignalStrength gsmSignalStrength)
{
initClass(gsmSignalStrength);
}
GsmSignalStrength gsmSignalStrength;
private void initClass(GsmSignalStrength gsmSignalStrength)
{
this.gsmSignalStrength = gsmSignalStrength;
}
}
文件 2“GsmSignalStrength”:
class GsmSignalStrength
{
GsmSignalStrength(byte signalStrength)
{
initClass(signalStrength);
}
GsmSignalStrength()
{
initClass(100);
}
byte value;
public void copyTo(GsmSignalStrength destination)
{
destination.value = this.value;
}
public GsmSignalStrength clone()
{
GsmSignalStrength clonedValue = new GsmSignalStrength();
this.copyTo(clonedValue);
return clonedValue;
}
/* With copy constructor
GsmSignalStrength(GsmSignalStrength gsmSignalStrength)
{
gsmSignalStrength.value = value;
}
*/
private void initClass(byte signalStrength)
{
this.value = signalStrength;
}
}
文件 5“GsmModemHandler”:
class GsmModemHandler
{
GsmModemHandler()
{
initClass();
}
private GsmSignalStrength m_gsmSignalStrength;
GsmSignalStrength getGsmSignalStrength()
{
...bla...
return m_gsmSignalStrength;
}
private void initClass()
{
m_gsmSignalStrength = new GsmSignalStrength();
}
}
文件 4“状态机”:
class StateMachine
{
StateMachine(GsmModemHandler gsmModemHandler)
{
initClass(gsmModemHandler);
}
private GsmModemHandler m_gsmModemHandler;
void doSomething()
{
GsmSignalStrength gsmSignalStrength = m_gsmModemHandler.getGsmSignalStrength();
Status xy = new Status(gsmSignalStrength.clone());
/* With copy constructor
GsmSignalStrength gsmSignalStrengthCopy = new GsmSignalStrength(gsmSignalStrength);
Status xy = new Status(gsmSignalStrengthCopy);
*/
}
private void initClass(GsmModemHandler gsmModemHandler)
{
m_gsmModemHandler = gsmModemHandler;
}
}