在系统中,往往有一些服务只需要它们在整个系统中只存在一个实例,而且可以在系统的任意角落访问到它,我们引入单件模式来解决这个问题,这是众多设计模式中的一种
class testSingleton { static testSingleton instance;//类的单例 private testSingleton{};//构造函数前的修饰符为私有;这样就不能在类的外部用new来生成//一个新的对象 public static testSingleton getInstance()//返回 单例 { if(instance == null) instance = new testSingleton(); return instance; } }
主要思想为确保一个类只拥有一个对像