代码 复制代码
1. public class Singleton {
2. private Singleton(){}
3. private static Singleton instance = new Singleton();
4. public static Singleton getInstance(){
5. return instance;
6. }
7. public void sys(String s){
8. System.out.println(s+"singleton.........");
9. }
10. }
# public class TestSingletion {
#
# public static void main(String args[]){
#
# Singleton.getInstance().sys("fdsfds");
# }
# }
第二种写法:
# public class Singleton {
# private static Singleton instance = null;
# private Singleton(){
# //应该加上这个
# }
# public static synchronized Singleton getInstance(){
# if(instance==null){
# instance = new Singleton();
# }
# return instance;
# }
# public void sys(String s){
# System.out.println(s+"singleton.........");
# }
# }
1. public class Singleton {
2. private Singleton(){}
3. private static Singleton instance = new Singleton();
4. public static Singleton getInstance(){
5. return instance;
6. }
7. public void sys(String s){
8. System.out.println(s+"singleton.........");
9. }
10. }
# public class TestSingletion {
#
# public static void main(String args[]){
#
# Singleton.getInstance().sys("fdsfds");
# }
# }
第二种写法:
# public class Singleton {
# private static Singleton instance = null;
# private Singleton(){
# //应该加上这个
# }
# public static synchronized Singleton getInstance(){
# if(instance==null){
# instance = new Singleton();
# }
# return instance;
# }
# public void sys(String s){
# System.out.println(s+"singleton.........");
# }
# }
本文介绍了两种实现单例模式的方法:一种是在类初始化时直接创建实例,另一种是在getInstance方法中检查实例是否存在并创建。通过具体代码示例展示了如何使用这两种方式。
19万+

被折叠的 条评论
为什么被折叠?



