饿汉模式 2022-11-03 Java Java 0 Comments Word Count: 241(words) Read Count: 1(minutes) Runtime 饿汉模式 饿汉 在对象加载时就创建对象 可能存在资源量浪费问题 懒汉 在调用 getInstance 才会创建 有线程安全问题 一、饿汉123456789101112131415161718192021222324252627282930package com.jhfuture.single_;public class SingleTon01 { public static void main(String[] args) {/** 饿汉模式 --->只能有一个对象* 1.构造器私有化 》防止直接 new* 2.类的内部创建对象* 3.向外暴露一个 getInstance方法。* */ System.out.println(GirlFriend.getInstance()); System.out.println(GirlFriend.getInstance()); }} class GirlFriend{ private String name; private static GirlFriend girlFriend = new GirlFriend("小谭"); public static GirlFriend getInstance(){ return girlFriend; } private GirlFriend(String name){ this.name=name; }} 二、懒汉1234567891011121314151617181920212223242526272829package com.jhfuture.single_;//懒汉模式//public class singleTon2 { public static void main(String[] args) { System.out.println(Cat.getInstance()); }}class Cat{ static Cat cat; static int age=99; private String name; public static Cat getInstance(){ if (cat==null){ cat=new Cat("小红"); } return cat; } public Cat(String name) { System.out.println("调用了"); this.name = name; } @Override public String toString() { return name; }}