java交换在运行时的实现

vsnjm48y  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(414)

我在写一个简单的聊天系统。通信应该有两种实现方式:
使用序列化
和xml(自己的协议)。
实现由用户在gui中选择。
那么,可以使用if else或switch来选择实现吗?
我曾经考虑过java反射,但是我不知道如何实现它。有什么建议吗?

7hiiyaii

7hiiyaii1#

我认为使用if-else或switch语句来选择实现是“可以的”。一个更好(更面向对象)的方法应该是这样的:

//////////////////////////////////
// The communication interfaces
//////////////////////////////////

public interface IChatCommunicationFactory {
    public String toString();
    public IChatCommunication create();
}

public interface IChatCommunication {
    public sendChatLine(String chatLine);
    public registerChatLineReceiver(IChatLineReceiver chatLineReceiver);
}

public interface IChatLineReceiver {
    public void onChatLineReceived(String chatLine);
}

//////////////////////////////////
// The communication interface implementations
//////////////////////////////////

public class XMLChatCommunicationFactory implements IChatCommunicationFactory {
    public String toString() {
        return "XML implementation";
    }

    public IChatCommunication create() {
        return new XMLChatCommunication();
    }
}

public class XMLChatCommunication implements IChatCommunication {
    private XMLProtocolSocket socket;

    public XMLChatCommunication() {
        // set up socket
    }

    public sendChatLine(String chatLine) {
        // send your chat line
    }

    public registerChatLineReceiver(IChatLineReceiver chatLineReceiver) {
        // start thread in which received chat lines are handled and then passed to the onChatLineReceived of the IChatLineReceiver
    }
}

// Do the same as above for the Serialization implementation.

//////////////////////////////////
// The user interface
//////////////////////////////////

public void fillListBoxWithCommuncationImplementations(ListBox listBox) {
    listBox.addItem(new XMLChatCommunicationFactory());
    listBox.addItem(new SerializationChatCommunicationFactory());
}

public IChatCommunication getChatCommunicationImplementationByUserSelection(ListBox listBox) {
    if (listBox.selectedItem == null)
        return null;

    IChatCommunicationFactory factory = (IChatCommunicationFactory)listBox.selectedItem;
    return factory.create();
}

您可以更进一步,实现类似 ChatCommunicationFactoryRegistry 每个 IChatCommunicationFactory 已注册。这将有助于将“业务”逻辑移出用户界面,因为 fillListBoxWithCommuncationImplementations() 方法只需要知道注册表,不再需要知道单个实现。

5fjcxozz

5fjcxozz2#

这里使用的“模式”是继承和简单的旧java。示例化要使用的实现,并在需要使用它的对象中保存对它的引用。当用户切换方法时,示例化新方法。

相关问题