我希望我的类只有一个实例 Format1 应该通过类引擎返回:
public final class Engine {
private static Format format;
public Engine(final Param1 param1, final Param2 param2) {
Engine.format = new FormatV1(param1); // FormatV1 implements Format
}
static Format getFormat(int condition) {
switch(condition) {
case 1 : return format;
}
}
}
这是否确保通过 getFormat 只返回一个正确的 Format 实例?
此外,调用 getFormat() 的客户端需要在格式对象(绝对没有状态)上执行方法,但将 ByteBuffer 传递给方法(此 ByteBuffer 可能会被修改):
class Client
{
public static void main(String[] args) {
Format obj = Engine.getFormat(1); // some param
ByteBuffer buffer; // read data from disk
synchronized (obj) {
long[] result = obj.method(buffer);
if (result == null) {
// do something
}
}
}
}
这里/这样的同步构造是否确保可序列化?
PS:我对Java很陌生,据我所知,我也可以使方法同步,但我认为检查(结果== null)也应该包含在关键部分中,所以我决定使用同步(obj ) 构造。如果这是一个愚蠢的问题,请原谅我,但我想确认我的怀疑。