いもづる オブジェクト指向

数計カウンター

(2006/09/02)

ここでは計数カウンターのクラスを作成します。 計数カウンターとは、野鳥を数えたり、交通調査などの時にカチカチッと押して数を数えているアレです。

コメントは省いていますが、このプログラムからどのようなカウンターのイメージができるか、 どのようにカプセル化されているかを読み取ってみてください。

 1|using System;
 2|
 3|namespace net.e_ioo.Sample
 4|{
 5|     public class NumberCounter
 6|    {
 7|        private long _maxCount = 0L;
 8|        private long _count    = 0L;
 9|        private int  _digit    = 0;
10|        private bool _isRotation = true;
11|
12|         public NumberCounter(int digit){
13|            if((digit < 1) || (10 < digit)){
14|                throw new Exception("桁値は 1 から 10 の範囲で設定してください");
15|            }
16|            this._digit = digit;
17|            this._maxCount = (long)(System.Math.Pow(10, digit)) - 1;
18|        }
19|
20|         public void Reset(){
21|            this._count = 0L;
22|        }
23|
24|         public void CountUp(){
25|            if(this._count < this._maxCount){
26|                this._count++;
27|            }else if(this._count <= this._maxCount){
28|                if(this._isRotation){
29|                    this.Reset(); 
30|                }
31|            }
32|        }
33|
34|         public int Digit{
35|            get{ return this._digit; }
36|        }
37|
38|         public long MaxCount{
39|            get{ return this._maxCount; }
40|        }
41|
42|         public bool IsRotation{
43|            get{ return this._isRotation;  }
44|            set{ this._isRotation = value; }
45|        }
46|
47|         public long Count{
48|            get{ return this._count; }
49|        }
50|    }
51|}

どうでしたか?このクラスのオブジェクトのイメージ像がわいたでしょうか?
このクラスの説明を箇条書きにします。

ちなみにクラス図は次のようになります。

カウンタークラス図

クラスはとにかく使ってもらってなんぼです。まずは、public部を考えましょう。

 1|using System;
 2|
 3|namespace net.e_ioo.Sample
 4|{
 5|    public class NumberCounter
 6|    {
 7|        public NumberCounter(int digit){
 8|        }
 9|
10|        public void Reset(){
11|        }
12|
13|        public void CountUp(){
14|        }
15|
16|        public long Count{
17|        }
18|
19|        public long Digit{
20|        }
21|
22|        public long MaxCount{
23|        }
24|
25|        public bool IsRotation{
26|        }
27|    }
28|}

もちろんクラス図を先に作成しますが、これができた時点で半分はできたようなものです。後は中身を実装するのみですね。

「隠蔽、隠蔽」のカプセル化でなく、「適切なユーザーインターフェースを提供する」というカプセル化を行いましょう。

実物カウンター
こんなイメージ!
(NumberCounter counter = new NumberCounter(4);)

 

webmaster@e-ioo.net