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
  • 相关阅读:
    移动函数的封装示例
    如何从不均衡类中进行机器学习
    DPM(Deformable Parts Model)--原理(一)
    K-means聚类算法
    机器学习中对核函数的理解
    总结:Bias(偏差),Error(误差),Variance(方差)及CV(交叉验证)
    技术干货
    神经网络入门
    目标函数、损失函数、代价函数
    地铁客流检测训练问题记录
  • 原文地址:https://www.cnblogs.com/zjc10203/p/9142825.html
Copyright © 2011-2022 走看看