首页 > 解决方案 > 使用哪种设计模式来获得想要的功能

问题描述

我想创建一个其他类继承的纯虚拟类,每个类实现相同的功能但具有不同的实现:假设我实现类 Server

class Server
{
   Server();
   ~Server()=0;
   virtual void send(const std::string& string);
   virtual std::string receive();
};

class TcpServer:public Server
{
   TcpServer();
   ~TcpServer();
   void send(const std::string& string)
   {...}
   std::string receive(){...}
};

class UdpServer : public Server
{
    UdpServer ();
    ~UdpServer ();
    void send(const std::string& string)
    {...}
    std::string receive(){...}
};



main()
{
    Server* server = new TcpServer()/UdpServer;
}

这种设计模式叫什么?因为我不明白它是 Adapter 还是 Composite 或 Facade,以及您是否对如何实现此行为有不同的想法。

标签: c++design-patternspolymorphism

解决方案


应该为此用例实施策略模式。检查下面的链接以获取更多信息。

https://en.m.wikipedia.org/wiki/Strategy_pattern


推荐阅读