zoukankan      html  css  js  c++  java
  • 使用伴生对象创建计数器工具类

    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
  • 相关阅读:
    jar
    8月21日23:38
    WPF之UI虚拟化
    (转)Windows系统白名单以及UAC机制
    C#获取文件版本信息
    命名实体识别,使用pyltp提取文本中的地址
    (转载)完成端口(Completion Port, I/OCP)详解
    全国各城市地名抓取,包含街道、村落、小区、商店、景点等
    关于Python打包运行的一些思路
    关于批判性思维(Critical Thinking)
  • 原文地址:https://www.cnblogs.com/zjc10203/p/9142825.html
Copyright © 2011-2022 走看看