单例(Singleton)模式是Java中最简单的设计模式之一。这种类型的设计模式属于创建模式,因为此模式提供了创建对象的最佳方法之一。
1.创建一个Singleton类
public class SingleObject { //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } }
2.从单例类中获取唯一的对象
public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject(); //Get the only object available SingleObject object = SingleObject.getInstance(); //show the message object.showMessage(); } }
3.验证输出
Hello World!