特集
2004/01/20 18:00:00 更新
特集:第3回 サンプルで学ぶCosminexusによる業務指向スタイル開発の流れ (3/7)
業務処理プログラム作成その1――Employee、Directoryクラスの作成――
業務処理プログラムの作成では、JBuilderを利用します。まず最初に、作成したプロジェクトにEmployee(従業員)クラスを新規作成してみましょう。
1. メニューから「ファイル」→「新規クラス」を選択すると、「クラスウィザード」が表示されます。
2. パッケージ名に「denwacho」、クラス名に「Employee」、ベースクラスに「java.io.Serializable」を一覧から選択し、「OK」ボタンをクリックします。
3. 生成されたひな形ソースを基に、業務処理にあたる以下のソース(リスト01)を記述します。
リスト01■Employee.javapackage denwacho; import java.io.Serializable; public class Employee implements Serializable { /** 名前 */ String name; /** 所属 */ String ou; /** 電話番号 */ String phone; public Employee(String name, String ou, String phone) { this.name = name; this.ou = ou; this.phone = phone; } public String getName() { return this.name; } public String getOu() { return this.ou; } public String getPhone() { return this.phone; } public void setName(String string) { this.name = string; } public void setOu(String string) { this.ou = string; } public void setPhone(String string) { this.phone = string; } } |
このクラスでは、nameという「名前」のフィールドを保持するようになっています。ほかにも、ouの「所属」、phoneの「電話番号」というフィールドを持たせます。これらのフィールドへのアクセスは、「get/set+フィールド名」というメソッドで行います。
次に、電話帳を表す「Directory」クラスを作成します。Directoryクラスでは複数の「Employee」クラスを管理しましょう。そのため、DirectoryクラスはEmployeeクラスを配列として持ちます。そのほか、追加メソッド(add)や、削除メソッド(del)なども定義します(リスト02)。
リスト02■Directory.javapackage denwacho; import java.util.Vector; import java.io.Serializable; import java.util.Iterator; public class Directory implements Serializable { private Vector employees; /* 社員リスト */ public Directory() { this.employees = new Vector(); } /** 社員追加 */ public void append(Employee emp) { this.employees.add(emp); } /** 削除 */ public void remove(int index) { this.employees.remove(index); } /** 削除 */ public void remove(String name) { Iterator i = this.employees.iterator(); int count = -1; while (i.hasNext()) { Employee emp = (Employee) i.next(); String str = emp.getName(); count++; if (name.equals(str)) { break; } } if (count != -1) { this.remove(count); } } /** 社員情報取得 */ public Employee getEmployee(int index) { return (Employee) this.employees.elementAt(index); } /** 登録件数 */ public int getLength() { return this.employees.size(); } } |
[清野泰正,ITmedia]
Copyright © ITmedia, Inc. All Rights Reserved.