java学习日记 构造方法私有化(单例设计、多例设计)

1、单例设计

class Singleton{
    private static final Singleton SINGLETON =new Singleton();
    public static Singleton getSingleton(){
        return SINGLETON;
    }
    private Singleton(){};   //构造方法私有化
    public void print(){
        System.out.println("Hello,world!");
    }
}
public class SingletonDemo1 {
    public static void main(String[] args) {
        Singleton single = Singleton.getSingleton();  //直接访问static属性
        Singleton single2 = Singleton.getSingleton();
        Singleton single3 = Singleton.getSingleton();
        Singleton single4 = Singleton.getSingleton();
        System.out.println(single);
        System.out.println(single2);
        System.out.println(single3);
        System.out.println(single4);
    }
}

输出结果:

com.hengqin.test1.Singleton@1b6d3586
com.hengqin.test1.Singleton@1b6d3586
com.hengqin.test1.Singleton@1b6d3586
com.hengqin.test1.Singleton@1b6d3586

代码意义:

要想控制一个类中实例化对象的个数,首先要锁定的就是类中的构造方法,因为在实例中声明任何新对象都要使用构造方法,如果构造方法被锁了,那就自然无法产生新的实例化对象。

可是既然要实例化一个对象,那么就可以在类的内部使用static方法来定义一个公共的对象,并且每一次通过static方法返回唯一的一个对象,这样外部不管有多少次调用,最终一个类只能产生唯一的一个对象,这样的设计就属于单例设计。

程序特点:

构造方法私有化,在类的内部定义static属性和方法,利用static方法取得本类的实例化对象,这样一来不管外部会产生多少个Singleton类的对象,但是本质上永远只有唯一的一个实例化对象。

2、多例设计

class Sex{
    private String title;
    private static final Sex MALE = new Sex("男");
    private static final Sex FEMALE = new Sex("女");
    private Sex(String title){
        this.title = title;
    }
    public String toString(){
        return this.title;
    }
    public static Sex getInstance(String title){
        if (title.equals("man")){
            return MALE;
        }else if (title.equals("woman")){
            return FEMALE;
        }else {
            return null;
        }
    }
}
public class MultiCaseDemo1 {
    public static void main(String[] args) {
        Sex sex = Sex.getInstance("man");
        System.out.println(sex);
    }
}
原文地址:https://www.cnblogs.com/cathycheng/p/13186688.html