//不知道这个能不能满足需求 class A { public static A defaultA = new A(); private A() { // ... } public A(String key) { // .... } public A getInstance(String key) { if (key == null) { return defaultA; } else { return new A(""); } } }
绝对不可以this = defaultA这种写法。 楼上的写法可以。但也可以使用单例模式来做。
===================== 不能满足. 有些情况下我要用上我说的功能. 比如:有可能我会在A的构造函数中调用 this = getInstance(xxx);
我记得以前在JDK的某个类中好象有类似我说的功能,但又不记得是那个类,我不知自己是否记错了.
LZ这样的想法本身就是有问题的,比如说this = getInstance(xxx); 这样根本就是行不通的 在一个等式的左边,java语法要求一定要是个变量~所以还是换个思维方式吧,呵呵 The left-hand side of an assignment must be a variable
class A { public static A defaultA = new A(); private A() { // ... } public A(String key) { // .... } public A getInstance(String key) { if (key == null) { return defaultA; } else { return new A(""); } }单态模式
我想先确定有没有直接实现我想法的写法。 如果没有"直接"的方法,其它方法再考虑. 我要 this = defaultA 类似这样的功能。
//不知道这个能不能满足需求
class A { public static A defaultA = new A(); private A() {
// ...
} public A(String key) {
// .... } public A getInstance(String key) {
if (key == null) {
return defaultA;
} else {
return new A("");
}
}
}
楼上的写法可以。但也可以使用单例模式来做。
不能满足. 有些情况下我要用上我说的功能. 比如:有可能我会在A的构造函数中调用 this = getInstance(xxx);
在一个等式的左边,java语法要求一定要是个变量~所以还是换个思维方式吧,呵呵
The left-hand side of an assignment must be a variable
// ...
} public A(String key) {
// .... } public A getInstance(String key) {
if (key == null) {
return defaultA;
} else {
return new A("");
}
}单态模式
我要 this = defaultA 类似这样的功能。