代码之家  ›  专栏  ›  技术社区  ›  konstantin_doncov

将两个完全不同的类作为一个类使用

  •  1
  • konstantin_doncov  · 技术社区  · 8 年前

    我有一个关于设计模式的愚蠢问题:假设我们有两个类 Post Product ,对于它们中的每一个,我们在数据库中有不同的表,它们之间没有任何共同之处,因此我们无法为它们创建基类。一些 Posts 即使 包含 Products .下面是我们应该如何处理它们:

    1. 以某种方式存储 邮递 产品 数据库中的实例,当用户从下一个项目请求新闻提要时,将它们打包到一个数组中(如果有必要,使用C++),将其发送到客户端,并在客户端接收和解包(使用Java)。
    2. 接下来,我们必须同时展示 邮递 产品 一个列表 (如Facebook上的新闻提要)。
    3. 还有,我们可以分享 邮递 产品 与我们的朋友使用聊天。所以我们可以发送 邮递 产品 作为消息的附件(因此,我们应该存储发送的id 邮递 产品 在列中 attached_item messages 服务器端数据库中的表)。

    那么,什么样的设计模式在这里是最好的呢?我应该如何实现 邮递 产品 课程?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Bentaye    8 年前

    这是一个非常广泛的问题,但这里有一个你能做什么的框架,只是给你一些想法:

    // An interface containing methods specific to objects you can list
    interface Listable {}
    
    // An interface containing methods specific to objects you can share
    interface Shareable {}
    
    // An interface containing methods specific to objects you can send
    interface Sendable {}
    
    class Post implements Listable, Shareable, Sendable {
        List<Product> products;
    }
    
    class Product implements Listable, Shareable, Sendable {
    }
    
    
    class ListManager {
        public void addToList(Listable element) { }
    }
    
    class ShareManager {
        public void share(Shareable element) { }
    }
    
    class SendManager {
        public void send(Sendable element) { }
    }
    

    然后您可以使用 Post Product 以这种方式互换:

    Post post = new Post();
    Product product = new Product();
    
    ListManager listManager = new ListManager();
    listManager.addToList(post);
    listManager.addToList(product);
    
    ShareManager shareManager = new ShareManager();
    shareManager.share(post);
    shareManager.share(product);
    
    SendManager sendManager = new SendManager();
    sendManager.send(post);
    sendManager.send(product);
    

    关于数据库表示,如建议 fusiled 在他的评论中,只需将它们放在两个单独的表格中即可。中间有一个映射表,用于将产品链接到其帖子。

    编辑 关于MESSAGES表的问题

    您可以添加一个新的映射表MESSAGE\u ATTACHED\u项和列 messageId ,则, postId ,则, productId 。将项目附加到邮件时,仅将值设置为相关列

    或者,另一种选择是使用仅具有id的附加\u ITEM表。 并使Post和Product表具有此表Id的外键。 然后,您可以将此attachedItemId粘贴到attached\u item列中

        2
  •  1
  •   fusiled    8 年前

    我认为解决方案可能比你想象的要简单。你为什么不用一个普通的 Java -喜欢界面并隐藏实现细节?

    只需使用所需的方法实现一个公共接口。假设调用此公共接口 EntityInterface :

    public class Post implements EntityInterface {};
    public class Product implements EntityInterface {};
    

    然后,当您想要处理这些类时,可以将它们视为 EntityInterface实体接口 对象:

    EntityInterface myNewPost = new Post();
    EntityInterface myNewProduct = new Product();
    //Now you see myNewProduct and myNewPost as EntityInterface objects
    

    这些代码片段位于 JAVA ,但在中使用虚拟函数 C++ 你也会得到同样的结果。