package com.maom.design.D_05_Singleton;
/**
* @Title: D_05_Singleton
* @Description: 05_单例模式
* @Author maohb
* @Version 1.0
*/
public class D_05_Singleton {
public static void main(String[] args) {
Person2 per = Person2.getPerson();
Person2 per2 = Person2.getPerson();
per.setName("zhangsan");
per2.setName("lisi");
System.out.println(per.getName());
System.out.println(per2.getName());
}
}
/** 饿汉式 */
class Person {
public static final Person person = new Person();
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//构造函数私有化
private Person() {
}
//提供一个全局的静态方法
public static Person getPerson() {
return person;
}
}
/** 懒汉式 */
class Person2 {
private String name;
private static Person2 person;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//构造函数私有化
private Person2() {
}
//提供一个全局的静态方法
public static Person2 getPerson() {
if(person == null) {
person = new Person2();
}
return person;
}
}
/** 同步锁 */
class Person3 {
private String name;
private static Person3 person;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//构造函数私有化
private Person3() {
}
//提供一个全局的静态方法,使用同步方法
public static synchronized Person3 getPerson() {
if(person == null) {
person = new Person3();
}
return person;
}
}
/** 双重检查 */
class Person4 {
private String name;
private static Person4 person;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//构造函数私有化
private Person4() {
}
//提供一个全局的静态方法
public static Person4 getPerson() {
if(person == null) {
synchronized (Person4.class) {
if(person == null) {
person = new Person4();
}
}
}
return person;
}
}
设计模式笔记_05_单例模式
最新推荐文章于 2024-09-10 17:07:09 发布