1 package com.cn; 2 3 public class Test { 4 public static void main(String agrs[]){ 5 Person p1 = Person.getInstances(); 6 Person p2 = Person.getInstances(); 7 System.out.println(p1==p2); 8 } 9 } 10 class Person{ 11 static Person person = new Person(); 12 private Person(){ 13 14 } 15 public static Person getInstances(){ 16 return person; 17 } 18 }
打印结果为 :true
保证了Person类在内存中只能被创建一个实例对象
时间: 2024-10-10 00:41:51