将一个类的构造函数声明为private,可以使得该类不被实例化,和不能被继承。
代码如下:
package test;
class Some{
private Some(){}
public static void dosome(){
System.out.println("dnali");
}
}
public class Singeleton {
public static void main(String[] args) {
//Some s=new Soem();无法实例化Some的对象
Some.dosome();
}
}
要创建这个类的实例,唯一的办法是提供一个公共静态方法。这种方式被称为单例模式。
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}