一、单例的作用是用于控制类的生成方式,而不让外部类任意new对象
1.Car.java
import java.util.ArrayList; import java.util.List; public class Car { //私有化构造函数,防止被外部的类new private Car() { } private static Car car = new Car(); //单例 private static List<Car> cars = new ArrayList<Car>(); //多例,类似连接池 public static Car getInstance() { return car; } public void run() { System.out.println("Car running..............."); } }
2.Test.java
public class Test { @org.junit.Test public void test() { Car car = Car.getInstance(); car.run(); Car car2 = Car.getInstance(); System.out.println(car == car2); System.out.println(car.equals(car2)); } }
运行结果: