本帖最后由 海是倒过来的天 于 2024-3-4 15:31 编辑
public interface DmPacket {
void write(DmPacketPayload packetPayload);
}
public class DmVersionResponsePacket_7_1_5_186 implements DmPacket {
@Override
public void write(DmPacketPayload packetPayload) {
// 实现你的逻辑
}
}
public class DmLoginResponsePacket_7_1_5_186 implements DmPacket {
@Override
public void write(DmPacketPayload packetPayload) {
// 实现你的逻辑
}
}
public class DmVersionResponsePacket_8_1_3_26 implements DmPacket {
@Override
public void write(DmPacketPayload packetPayload) {
// 实现你的逻辑
}
}
public class DmLoginResponsePacket_8_1_3_26 implements DmPacket {
@Override
public void write(DmPacketPayload packetPayload) {
// 实现你的逻辑
}
}
public class DmPacketFactory {
private static final Map<Integer, Map<String, DmPacket>> PACKET_MAP = new HashMap<>();
static {
// 初始化 map
Map<String, DmPacket> version7_1_5_186Packets = new HashMap<>();
version7_1_5_186Packets.put(CLIENT_VERSION.getValue(), new DmVersionResponsePacket_7_1_5_186());
version7_1_5_186Packets.put(LOGIN.getValue(), new DmLoginResponsePacket_7_1_5_186());
PACKET_MAP.put("7.1.5.186", version7_1_5_186Packets);
Map<String, DmPacket> version8_1_3_26Packets = new HashMap<>();
version8_1_3_26Packets.put(CLIENT_VERSION.getValue(), new DmVersionResponsePacket_8_1_3_26());
version8_1_3_26Packets.put(LOGIN.getValue(), new DmLoginResponsePacket_8_1_3_26());
PACKET_MAP.put("8.1.3.26", version8_1_3_26Packets);
}
public static DmPacket getDmPacket(int contentType, String version) {
Map<String, DmPacket> versionPackets = PACKET_MAP.get(version);
if (versionPackets != null) {
return versionPackets.get(contentType);
}
return null; // 或者抛出异常
}
}
private void getDmPacket(int contentType, DmPacketPayload packetPayload) {
DmPacket dmPacket = DmPacketFactory.getDmPacket(contentType, DmVersion.getVersion());
if (dmPacket != null) {
dmPacket.write(packetPayload);
} else {
// 处理未找到对应包的情况
}
}
如果你需要添加新的 DmPacket 类,你只需要在工厂类中添加新的映射关系就可以了
|