publicclassStudent{//1.构造方法私有化privateStudent(){}//2.提供一个集合,集合中存储本类对象privatestatic List<Student> stuList =newArrayList<>();static{//初始化50个Student对象,存储到集合for(int i =0; i <50; i++){
stuList.add(newStudent());}}//3.定义公有、静态方法,随机获取集合中的一个Student对象publicstaticsynchronized Student getInstance(){
Random random =newRandom();int i = random.nextInt(stuList.size());return stuList.get(i);}}
publicclassStudent{private String name;publicStudent(String name, Sex sex){this.name = name;this.sex = sex;}public String getName(){return name;}publicvoidsetName(String name){this.name = name;}public Sex getSex(){return sex;}publicvoidsetSex(Sex sex){this.sex = sex;}private Sex sex;@Overridepublic String toString(){return"Student{"+"name='"+ name +'\''+", sex="+ sex +'}';}}//多例模式的Sex类classSex{//1.构造方法私有化privateSex(String sex){this.sex = sex;}private String sex;//2.提供两个公有、静态、final的本类对象引用publicstaticfinal Sex MAN =newSex("男");publicstaticfinal Sex WOMEN =newSex("女");@Overridepublic String toString(){return sex;}}