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

    单例设计模式----就是保证一个类只有一个对象   

    a.将构造方法设置成私有方法
    b.在类内部自己创建一个静态的本类对象
    c.提供一个静态方法用于获取该对象
    d.别的类中想要获取对象可以通过调用这个类的静态方法获取

    //单例设计模式
    //懒汉
    public class Gril {
        private String name;
        private String sex;
        private static final Gril gril = new Gril();
        private Gril(String name, String sex) {
            this.name = name;
            this.sex = sex;
        }
    
        private Gril() {
        }
    
        public static Gril getGril(){
            return gril;
        }
    }
    //单例设计模式
    //饿汉
    public class Boy {
        private String name;
        private String sex;
        private static Boy boy = null;
    
        private Boy() {
        }
    
        private Boy(String name, String sex) {
            this.name = name;
            this.sex = sex;
        }
    
        public synchronized static Boy getBoy() {
            boy = boy == null ? new Boy() : boy;
            return boy;
        }
    }

    多例设计模式---就是保证一个类只有指定个数的对象  

    a.将构造方法设置成私有方法
    b.在本类的内部创建一个静态集合,保存多个对象
    c.在本类中提供一个静态方法,随机返回集合中某个对象
    d.在测试类中调用静态方法获取对象

    public class MoreObj {
        //多例设计模式
        private static ArrayList<MoreObj> arrayList = new ArrayList<>();
    
        static {
            Collections.addAll(arrayList, new MoreObj(), new MoreObj(), new MoreObj());
        }
    
        public static MoreObj getInstance(){
            return arrayList.get(new Random().nextInt(arrayList.size()));
        }
    }
     
  • 相关阅读:
    理解HashSet及使用
    Java 集合类详解
    Java-泛型编程-使用通配符? extends 和 ? super
    回调函数及其用法
    log4j.properties 详解与配置步骤
    约瑟夫环
    泛型的约束与局限性
    把代码字体加大的办法
    System.arraycopy方法
    泛型数组列表与反射
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/13261241.html
Copyright © 2011-2022 走看看