さまざまな種類のバイナリ パケットを送受信するネットワーク アプリを作成しています。新しい種類のパケットをアプリにできるだけ簡単に追加できるようにしようとしています。
ここでは、Packet
クラスを作成し、さまざまな種類のパケットごとにそのサブクラスを作成します。ただし、見た目ほどきれいではありません。私はこのようなコードで終わった:
static class ItemDesc extends Packet {
public final int item_id;
public final int desc_type;
public final String filename;
public final String buf;
public ItemDesc(Type t, int item_id, int desc_type, String filename, String buf) {
super(t); // sets type for use in packet header
this.item_id = item_id;
this.desc_type = desc_type;
this.filename = filename;
this.buf = buf;
}
public ItemDesc(InputStream i) throws IOException {
super(i); // reads packet header and sets this.input
item_id = input.readInt();
desc_type = input.readByte();
filename = input.readStringWithLength();
buf = input.readStringWithLength();
}
public void writeTo(OutputStream o) throws IOException {
MyOutputStream dataOutput = new MyOutputStream();
dataOutput.writeInt(item_id);
dataOutput.writeByte(desc_type);
dataOutput.writeStringWithLength(filename);
dataOutput.writeStringWithLength(buf);
super.write(dataOutput.toByteArray(), o);
}
}
このアプローチで気になるのは、コードの繰り返しです。パケット構造を 4 回繰り返しています。これを避けたいのですが、単純化する合理的な方法がわかりません。
Python で書いていたら、考えられるすべてのフィールド タイプのディクショナリを作成し、次のように新しいパケット タイプを定義します。
ItemDesc = [('item_id', 'int'), ('desc_type', 'byte'), ...]
どの関数型言語でも同様のことができると思います。ただし、このアプローチを Java に適用する方法がわかりません。
(多分、私はあまりにも衒学的であるか、関数型プログラミングとコードを書くコードを書くことに慣れていたので、繰り返しを避けることができました:))
ご提案いただきありがとうございます。