参考文章:【深入学习设计模式】——单例模式
package singleton;
/**饿汉式:存在资源浪费问题*/
class Singleton01{
private Singleton01(){}
private static Singleton01 instance= new Singleton01();
public static Singleton01 getInstance(){
return instance;
}
//public static void show(){}
}
/**懒汉式:存在线程安全问题*/
class Singleton02{
private Singleton02(){}
private static Singleton02 instance=null;
public static Singleton02 getInstance(){
if(instance==null){
instance=new Singleton02();
}
return instance;
}
}
/**使用synchronized关键字解决并发问题:在访问量大的时候会非常的影响性能*/
class Singleton03{
private Singleton03(){}
private static Singleton03 instance=null;
public static synchronized Singleton03 getInstance(){
if(instance==null){
instance=new Singleton03();
}
return instance;
}
}
/**双重检查机制*/
class Singleton04{
private Singleton04(){}
private static Singleton04 instance=null;
public static synchronized Singleton04 getInstance(){
if(instance==null){
//给类对象(即字节码对象)加锁
synchronized (Singleton04.class) {
if(instance==null){
instance=new Singleton04();
}
}
}
return instance;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestSingleton {
public static void main(String[] args) {
Singleton04 s1=Singleton04.getInstance();
Singleton04 s2=Singleton04.getInstance();
System.out.println(s1==s2);//true
s1.setName("zhangsan");
s2.setName("lisi");
System.out.println(s1.getName());//lisi
System.out.println(s2.getName());//lisi
}
}
package singleton;
/**饿汉式:存在资源浪费问题*/
class Person01{
public static final Person01 person = new Person01();
private Person01() {}
public static Person01 getPerson() {
return person;
}
}
/**懒汉式:存在线程安全问题*/
class Person02{
private static Person02 person;
private Person02() { }
public static Person02 getPerson() {
if(person == null) {
person = new Person02();
}
return person;
}
}
/**使用synchronized关键字解决并发问题:在访问量大的时候会非常的影响性能*/
class Person03{
private static Person03 person;
private Person03() {}
public static synchronized Person03 getPerson() {
if(person == null) {
person = new Person03();
}
return person;
}
}
/**双重检查机制*/
class Person04{
private static Person04 person;
private Person04() {}
public static Person04 getPerson() {
if(person == null) {
//给类对象(即字节码对象)加锁
synchronized (Person04.class) {
if(person == null) {
person = new Person04();
}
}
}
return person;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestSingleton2 {
public static void main(String[] args) {
Person04 s1 = Person04.getPerson();
Person04 s2 = Person04.getPerson();
System.out.println(s1==s2);//true
s1.setName("zhangsan");
s2.setName("lisi");
System.out.println(s1.getName());//lisi
System.out.println(s2.getName());//lisi
}
}