首先,我们考虑一个已有的架构设计。Directory Server其实就是一个很好的例子,假定这个server含有用户信息,每个用户登陆需要与这个server联络检查用户名、密码以及用户的entitlements(请问中文怎么翻译?)等。你的公司可能有10个系统(每个系统可能有一个或者多个JVM),但用户的信息只有一套,这叫做单点登陆(SSO Single Sign On)。
yes, the idea is simple and clear: set a counter at a place that accessible from 3 JVMs, like file, DB, JMS, Ldap and others like jeffyan77 mentioned. And we might transfer the singlton among them.
For implementation, the same issue is synchronization like in single JMV version.
truezerg(赵明宇) :如果你同意我对单例概念的定义,那么很希望你举一个既是不变类又是用了单例模式的例子出来,我会很高兴能更正自己认识上的错误. 如果你认同ajoo(聪明的一猪)单例的定义,就没必要再举例了, 我想我们的基础概念不同.
---------------------------------------------------------------------------------
many fly weight objects are both immutable and singleton. In the first version of Java compiler, one sub-optimization is: all String objects with same value share a single copy in memory.
ajoo(聪明的一猪) ,你的给出的例子,小错误可真多,我修改正了一下,如下
interface List {
boolean isEmpty();
List cons(Object o);
List tail();
}
class NilList implements List { //可以singleton。
private static final List singleton = new NilList();
private NilList() {}
public boolean isEmpty() {
return true;
}
public List cons(Object o) {
return new ConsList(o, this);
}
public List tail() {
throw new UnsupportedOperationException();
}
public static final List instance() {
return singleton;
}
}
class ConsList implements List { //无法singleton
private final List tl;
private final Object hd;
public boolean isEmpty() {
return false;
}
public List cons(Object o) {
return new ConsList(o, this);
}
public List tail() {
return tl;
}
public ConsList(Object h, List t) {
this.hd = h;
this.tl = t;
}
}