using System;
/*
例5-2
文字型データ用のQueueクラス
*/
interface IFSample<T>
{
void Put(T obj);
T Get();
}
class SimpleQueue<T> : IFSample<T>
{
public T[] q; // キューのデータを保持する配列
public int putloc, getloc; // put操作やget操作用の添え字
public SimpleQueue(int size) {
q = new T[size + 1]; // キュー用にメモリを確保する
putloc = getloc = 0;
}
// 1文字分だけキューに追加する
public void Put(T obj) {
if (putloc == q.Length - 1)
{
Console.WriteLine(" -- Queue is full.");
return;
}
putloc++;
q[putloc] = obj;
}
// キューから1文字分だけ取り出す
public T Get()
{
if (getloc == putloc)
{
Console.WriteLine(" -- Queue is empty.");
throw new Exception();
}
getloc++;
return q[getloc];
}
}
// Queueクラスを使う
class QDemo
{
static void Main()
{
SimpleQueue<char> bigQ = new SimpleQueue<char>(100);
SimpleQueue<int> smallQ = new SimpleQueue<int>(5);
char ch;
int i;
Console.WriteLine("Using bigQ to store the alphabet.");
// bigQにいくつかの文字を追加する
for (i = 0; i < 26; i++)
bigQ.Put((char)('A' + i));
// bigQから取り出して表示する
Console.Write("Contents of bigQ: ");
for (i = 0; i < 26; i++)
{
ch = bigQ.Get();
if (ch != (char)0) Console.Write(ch);
}
Console.WriteLine("\n");
Console.WriteLine("Using smallQ to store integer.");
// smallQを使ってエラーを起こさせる
for (i = 0; i < 5; i++)
{
Console.Write("Attempting to store " + i);
smallQ.Put(i);
Console.WriteLine();
}
Console.WriteLine();
// さらにsmallQでエラーを起こさせる
Console.Write("Contents of smallQ: ");
int g;
for (i = 0; i < 5; i++)
{
g = smallQ.Get();
Console.Write(g);
}
}
}
この場合、インターフェイスはクラスのプロトタイプみたいなものですが、自分的にはあとから、こうも書けるみたいな感じが好きなので、前のものを直してみました。