//////////////////////////////////
// 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();
}
2条答案
按热度按时间7hiiyaii1#
我认为使用if-else或switch语句来选择实现是“可以的”。一个更好(更面向对象)的方法应该是这样的:
您可以更进一步,实现类似
ChatCommunicationFactoryRegistry
每个IChatCommunicationFactory
已注册。这将有助于将“业务”逻辑移出用户界面,因为fillListBoxWithCommuncationImplementations()
方法只需要知道注册表,不再需要知道单个实现。5fjcxozz2#
这里使用的“模式”是继承和简单的旧java。示例化要使用的实现,并在需要使用它的对象中保存对它的引用。当用户切换方法时,示例化新方法。