单例模式的学习与简单应用
昨天晚上睡觉的时候,偶尔浏览了一下单例模式,听说了好久,也没有正真用心去看,没想到今天和同事交流的时候发现自己记得还是比较清楚。只是对于实际应用没有练习过,转没记一篇,边学边补充。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Singleton{ 2 private static Singleton instance = new Singleton(); 3 private String name; 4 5 private Singleton(){}; 6 public static Singleton getInstance(){ 7 return instance; 8 } 9 10 public String getName(){ 11 return name; 12 } 13 public void setName(String name){ 14 this.name = name; 15 } 16 public void printInfo(){ 17 System.out.println("name is "+ name); 18 } 19 20 } 21 22 public class TestMain{ 23 public static void main(String[] args){ 24 Singleton tsa = Singleton.getInstance(); 25 26 Singleton ts2 = Singleton.getInstance(); 27 ts2.setName("bilibili"); 28 tsa.setName("a234"); 29 30 tsa.printInfo(); 31 ts2.printInfo(); 32 33 System.out.println(tsa == ts2?"单例模式成功":"失败"); 34 35 } 36 }
自己进行参考代码重复时出现的问题:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Singleton{ 2 private static Singleton instance = new Singleton(); 3 private Singleton(){}; 4 public static Singleton getInstance(){ 5 return instance; 6 } 7 } 8 public String getName(){ 9 return name; 10 } 11 public void setName(){ 12 this.name = name; 13 } 14 public void printInfo(){ 15 System.out.println("name is "+ name); 16 } 17 18 19 20 public class TestMain{ 21 public staic void main(String[] args){ 22 TestString ts1 = Singleton.getInstance(); 23 ts1.setName("基础"); 24 TestString ts2 = Singleton.getInstance(); 25 ts2.setName("bilibili"); 26 27 ts1.printInfo(); 28 ts2.printInfo(); 29 30 System.out.println(ts1 == ts2?"无知":"失败"); 31 32 } 33 }
1、连最基本的Java基础都没有了,对于基本的public类的理解都是空白;
2、方法属性什么的在脑子里根本就没有概念;
3、什么叫作无知;
…………
参看文章:http://blog.csdn.net/jason0539/article/details/23297037
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class TestSingleton { 2 String name = null; 3 4 private TestSingleton() { 5 } 6 7 private static volatile TestSingleton instance = null; 8 9 public static TestSingleton getInstance() { 10 if (instance == null) { 11 synchronized (TestSingleton.class) { 12 if (instance == null) { 13 instance = new TestSingleton(); 14 } 15 } 16 } 17 return instance; 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public void printInfo() { 29 System.out.println("the name is " + name); 30 } 31 32 } 33 34 public class TestMain{ 35 public static void main(String[] args){ 36 TestSingleton ts1 = TestSingleton.getInstance(); 37 ts1.setName("a234"); 38 TestSingleton ts2 = TestSingleton.getInstance(); 39 ts2.setName("Data"); 40 41 42 ts1.printInfo(); 43 ts2.printInfo(); 44 45 System.out.println(ts1 == ts2); 46 47 } 48 }
---------------------------------------------------151104jingshuyuan-