1 Star 2 Fork 1

csbooks/OnJava8-Code

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
SingletonPattern.java 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
Bruce Eckel 提交于 2017-05-02 04:33 +08:00 . Checkstyle passing
// patterns/SingletonPattern.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
interface Resource {
int getValue();
void setValue(int x);
}
// Since this isn't inherited from a Cloneable
// base class and cloneability isn't added,
// making it final prevents cloneability from
// being added through inheritance. This also
// implements thread-safe lazy initialization:
final class Singleton {
private static final class
ResourceImpl implements Resource {
private int i;
private ResourceImpl(int i) {
this.i = i;
}
public synchronized int getValue() {
return i;
}
public synchronized void setValue(int x) {
i = x;
}
}
private static class ResourceHolder {
private static Resource resource =
new ResourceImpl(47);
}
public static Resource getResource() {
return ResourceHolder.resource;
}
}
public class SingletonPattern {
public static void main(String[] args) {
Resource r = Singleton.getResource();
System.out.println(r.getValue());
Resource s2 = Singleton.getResource();
s2.setValue(9);
System.out.println(r.getValue());
try {
// Can't do this: compile-time error.
// Singleton s3 = (Singleton)s2.clone();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
/* Output:
47
9
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/javabook/OnJava8-Code.git
git@gitee.com:javabook/OnJava8-Code.git
javabook
OnJava8-Code
OnJava8-Code
master

搜索帮助