单例模式和多例模式

简介: 单例模式和多例模式
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);
    }
}
相关文章
|
1月前
|
设计模式 安全 测试技术
【C++】—— 单例模式详解
【C++】—— 单例模式详解
|
4天前
|
设计模式
单例模式
单例模式
11 0
|
3月前
|
C++
【C++ 单例模式】
【C++ 单例模式】
|
4月前
|
安全 C++
C++单例模式
C++单例模式
30 1
|
4月前
|
设计模式 安全
【单例模式】—— 每天一点小知识
【单例模式】—— 每天一点小知识
|
8月前
|
设计模式 Java Spring
什么场景要使用单例模式,什么场景不能使用?
经常有小伙伴问我,设计模式学了这么久,每次看到概念也都能理解。但是,就是不知道怎么用,在哪里能用?我告诉大家,设计模式,不是为了要用而用的,而是作为前人总结下来的经验,等到哪天需要用的时候,你能想起来为你所用。
65 0
|
11月前
|
SQL 安全 Java
五种单例模式介绍
五种单例模式介绍
66 0
|
设计模式 缓存 JavaScript
什么是单例模式?怎么生成单例类? - 1/14
什么是单例模式?怎么生成单例类? - 1/14
55 0
|
安全 Java
单例模式和多例模式(懒汉式和饿汉式)
单例模式和多例模式(懒汉式和饿汉式)
111 0
|
设计模式 数据库 Python