public class test9 { // 单例模式:懒汉 // 所有的请求都用同一个对象处理,节省内存 private static test9 test9; private test9(){ //构造器私有,防止外界调用 } public static test9 getobject(){ if(test9==null){ test9=new test9(); } return test9; } }
public class test10 { // 饿汉模式 private static test10 test10=new test10();; private test10(){ } public static test10 getTest10(){ return test10; } }
import java.util.ArrayList; import java.util.Random; /*多例模式, 每次请求都用不同的对象,防止并发问题的产生 * */ public class test11 { // 对象数量 private static final int N=10; // 装对象的容器 private static ArrayList<test11> list = new ArrayList<test11>(N);; private test11(int num){ System.out.println("creat "+num); } static{ // 实例化全部对象 for (int i = 0; i < N; i++) { list.add(new test11(i)); } } public static test11 getTest11(){ // 获取随机数,实例化集合中对应索引的对象 Random random=new Random(); int r=random.nextInt(N); return list.get(r); } }