这是我第一次参与为外部服务器编写完整的客户端(我对设计模式非常陌生)。
该服务器提供了几种协议(protocol)来连接和发送命令,例如REST、SOAP 等等。
所有这些协议(protocol)执行几乎相同的一组操作,但有所不同。我需要为其设计和实现一个完整的客户端框架,它将支持所有这些协议(protocol)。
根据理解并浏览了几个互联网链接,在我看来,应该使用抽象工厂模式和接口(interface)。
我目前的实现思路如下:
为Connection创建一个抽象工厂类(ConnectionFactory)。根据输入,提及要使用的协议(protocol),将创建相应的 Connection 对象。这个抽象类将有一个抽象方法(processMessage)。该方法必须在所有协议(protocol)的连接类中实现。这个方法(processMessage)将采用一个参数来提及要执行的请求类型。每个协议(protocol)都有一个单独的请求名称。我如何使用常量来处理它?</p>
定义请求、响应和客户端的接口(interface)。所有协议(protocol)都有自己的请求、响应和客户端类,它们将实现各自的接口(interface)。
请向我提供有关此设计的宝贵意见;请给我建议更好的东西,我可以在这里做。 我仍然无法最终确定目录结构,请帮助我。
最佳答案
如果您计划为不同协议(protocol)定义类层次结构,请尽量避免为数据类型(请求、响应等)创建并行层次结构。这通常被认为是一种反模式,并被称为“并行继承层次结构”。这是一个例子question 。这种方法的主要缺点是必须维护多个并行的类层次结构。
创建连接工厂听起来很合理。它很可能会返回一个类实例,该实例具有用于向服务器发送消息的 createMessage() 方法和用于从服务器接收消息的 processMessage() 方法em>服务器和工厂将插入接下来解释的 ProtocolHandler。
对于请求和响应,您可以使用 Strategy pattern 在 Connection 类中定义 ProtocolHandler 成员。 ,其中每个实现都是一个类,可以处理、解析、编码等相应协议(protocol)(REST、SOAP 等)的详细信息。 Connection 类 processMessage() 和 createMessage() 方法将使用 ProtocolHandler 类层次结构。
这是一些 C++ 伪代码,我尚未编译或测试它,但我希望它能让您很好地了解我试图解释的内容。
// Your factory will create the Connection instance and fill in the
// corresponding ProtocolHandler concrete implementation instance
class Connection
{
public:
// Depending on what else you need for the Connection,
// the constructors may be different
Connection() : handler_(NULL) {}
Connection(ProtocolHandler *handler) : handler_(handler) {}
inline void setProtocolHandler(ProtocolHandler *handler) {handler_ = handler;}
inline ProtocolHandler *getProtocolHandler() {return handler_;}
void processMessage(const string &msg) {
handler_->decode(msg);
// any extra logic here
}
string createMessage() {
// any extra logic here
return handler_->encode();
}
// Put the rest of your connection stuff here
private:
ProtocolHandler *handler_;
};
// Notice that Im handling the protocol msg buffers in a std::string, this
// may or may not work for you, replace accordingly depending on your needs
class ProtocolHandler
{
public:
// abstract methods
// name these accordingly as handle, parse, marshal, etc
virtual string encode() = 0;
virtual void decode(const string &msg) = 0;
// Other methods you may need here
};
class RestProtocolHandler : public ProtocolHandler
{
public:
virtual string encode() { /* your rest msg encode impl here */ }
virtual void decode(const string &msg) { /* your rest msg decode impl here */ }
// Other methods and/or attributes you may need here
};
// More concrete ProtocolHandler implementations here
关于oop - 为支持多协议(protocol)的服务器设计客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114079/