package excise.day02 /** * 单例模式,实现计数器 */ class SingletonInstance private { //用 private 关键字修饰,这样就只有伴生对象一个对象了,有效防止外部实例化 SingletonInstance 类 //只能供对应伴生对象使用 override def toString = "This is a counter Class " protected var counter = 0 // protected 伴生对象可访问, private 伴生对象也访问不了 } object SingletonInstance{ private val singleton = new SingletonInstance def getInstance: SingletonInstance = singleton def f_counter_plus_one : Int= { singleton.counter += 1 singleton.counter } def f_counter_minus_one : Int= { singleton.counter -= 1 singleton.counter } def f_show_current_counter : String = { // 这里不知道怎么消除黄色警告,返回类型用Unit也不行,只好借助返回一个空字符串 println( "The current value of counter is : "+singleton.counter) "" } def f_get_current_counter : Int = { singleton.counter } } object SingletonInstanceTest { def main(args: Array[String]): Unit = { SingletonInstance.f_show_current_counter SingletonInstance.f_counter_plus_one SingletonInstance.f_show_current_counter SingletonInstance.f_counter_plus_one SingletonInstance.f_show_current_counter SingletonInstance.f_counter_plus_one SingletonInstance.f_show_current_counter SingletonInstance.f_counter_minus_one SingletonInstance.f_show_current_counter SingletonInstance.f_counter_plus_one SingletonInstance.f_show_current_counter } }
使用伴生对象创建计数器工具类
输出结果:
The current value of counter is : 0 The current value of counter is : 1 The current value of counter is : 2 The current value of counter is : 3 The current value of counter is : 2 The current value of counter is : 3