标签:ati 设计模式 性能 静态 懒汉 单例 com for 一个
? 某个类有且只能有一个对象,如:用这个对象记录只有一个用户的信息
/**
* 单例模式
* 饿汉式
*/
public class Program1 {
public static void main(String args[]) {
User user = User.getInstance();
//测试部分
for (int i = 0; i < 100; i++) {
User u = User.getInstance();
if(u != user){
System.out.println("一个新的类被实例化了");
}
}
System.out.println("程序结束");
}
}
/**
* 作为一个单例模式,使其在程序中有且只能有一个实例
*/
class User {
//1.private构造方法,类外不能new
private User() {
}
//2.设计一个private static的当前类的对象,并new
private static User instance = new User();
/*static {
User instance = new User();
}*/
//3.提供一个static方法,可以返回给调用方一个当前类的对象
public static User getInstance() {
return instance;
}
}
25行:private User() {}
为什么要private
?
防止User user = new User();
,实例化多个不同的对象
30行:private static User instance = new User();
中为什么要private
和static
?
private
:
main
中:User user = null;
static
:
static的
instance`存在静态存储区,每次调用时,都指向的同一个对象,保证单例;
通过static
的getInstance
方法获取instance
,如果instance
非静态,无法被getInstance
调用;
38行:public static User getInstance(){}
中为什么要static
?
instance
是static
的
private static User instance = new User();
? 程序开始就实例化好了,造成了不必要的性能损耗与空间损耗;
/**
* 单例模式
* 懒汉式
*/
public class Program2 {
public static void main(String args[]){
Teacher teacher = Teacher.getInstance();
}
}
class Teacher {
//1.private构造方法
private Teacher(){
//测试
System.out.println("实例化了一个新的对象");
}
//2.设计一个private static的当前类的对象
private static Teacher instance;
//3.设计一个static方法,若对象为null,则new,然后返回该对象
public static Teacher getInstance(){
if(instance == null) {
instance = new Teacher();
}
return instance;
}
}
private构造方法
设计一个private static的当前类的对象
提供一个synchronized static方法,如果对象为null,就new,然后返回一个当前类的对象
package com.yuebanquan.singleton;
public class Program3 {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread t = new Thread(() ->{
Chairman chairman = Chairman.getInstance();
});
t.start();
}
}
}
class Chairman {
private Chairman() {
System.out.println("一个新的对象被实例化了");
}
private static Chairman instance;
//线程同步,防止线程不安全
public static synchronized Chairman getInstance() {
if (instance == null) {
instance = new Chairman();
}
return instance;
}
}
第23行public static synchronized Chairman getInstance()
中,为什么要用synchronized
?
因为synchronized`使得后续的线程需要使用该方法时需要等待,直到前面的线程运行完该方法,防止线程不安全
相较于饿汉式,省性能与空间
在懒汉式基础上改进,防止了线程不安全
标签:ati 设计模式 性能 静态 懒汉 单例 com for 一个
原文地址:https://www.cnblogs.com/yuebanquan/p/10947120.html