单例模式是Java中最简单的设计模式之一。 这种设计模式属于创建模式,因为该模式提供了创建对象的最佳方法之一。
该模式涉及单个类,该类负责创建对象,同时确保仅创建单个对象。 此类提供了一种访问其唯一对象的方法,该对象可以直接访问而无需实例化该类的对象。
实现
我们将创建一个SingleObject类。 SingleObject类具有专用的构造函数,并且具有其自身的静态实例。
SingleObject类提供了一个静态方法来将其静态实例传递给外界。 SingletonPatternDemo,我们的演示类将使用SingleObject类来获取SingleObject对象。
Step 1
Create a Singleton Class.
SingleObject.java
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!");
}
}
Step 2
Get the only object from the singleton class.
SingletonPatternDemo.java
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();
}
}
Step 3
Verify the output.
Hello World!