单例模式和多例

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

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()));
    }
}
 
原文地址:https://www.cnblogs.com/xiaozhang666/p/13261241.html