zoukankan      html  css  js  c++  java
  • java单例模式和双例模式

    今天朋友找我给做道题,双例模式,我是没听说过,都说是单例模式和多例模式,

    也不知道双例模式什么时候用,就简单写了一个案例,不知道对不对,个人感觉蛮对的,双例就是单例+单例,废话不说了!!!!

    /*
    *单例模式
    调用方法
    Singleton singleton = Singleton.getSingleton();
    singleton.getValue("我是单例模式");
    */
     
    public class Singleton {
        private static Singleton  singleton = null;
        public static Singleton getSingleton(){
            if(singleton==null){
                return singleton = new Singleton();
            }else{
                return singleton;
            }
        }
        
        public String getValue(String name){
            return name;
        }
    }
    
    /*
    *双例模式,如果是三例模式就吧len参数改成3
    调用方法
    Doubleton doubleton = Doubleton.getDoubleton();
    doubleton.getValue("我有两个实例!");
    */
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Doubleton {
    
        private static List<Doubleton> list = new ArrayList<Doubleton>();
        private static int len = 2;
        static{
            for(int i=0;i<len;i++){
                list.add(new Doubleton());
            }
        }
        public static Doubleton getDoubleton (){
            Random random = new Random();
            int current = random.nextInt(len);
            return (Doubleton)list.get(current);
        }
        
    
        public String getValue(String name){
            return name;
        }
    }

    希望大牛们给指点指点对不对,在此感谢!!!!

  • 相关阅读:
    限制TextBox框 所输入的字符数
    ASP.NET中使用AJAX后,Session丢失异常的自定义处理。
    用div替代模态窗口
    自动更新程序的制作方法
    常用SQL语句集合
    GridView无数据显示表头类
    密码强度
    GridView绑定技巧终结者
    js验证输入是否为手机号码或电话号码
    Js事件列表
  • 原文地址:https://www.cnblogs.com/tongchuanxing/p/5653485.html
Copyright © 2011-2022 走看看