两个相互依赖的对象。那不好吗? [英] Two objects with dependencies for each other. Is that bad?

查看:124
本文介绍了两个相互依赖的对象。那不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我为我的项目建立自己的系统时,我正在学习很多设计模式。我想问一个关于一个设计问题,我找不到答案。



目前我正在建立一个使用套接字的聊天服务器,多个客户端。现在我有三个课程:


  1. 个人类,其中包含nick,age和Room-

  2. 房间类,其中包含房间名称,主题和目前在该房间中的人员列表。

  3. 酒店级,其中包含人员列表和服务器上的房间列表。

我已经做了一个图来说明:



我有一个服务器上的人员列表,上课,因为跟踪现在有多少线上线(不必遍历所有的房间)是很好的。
这些人住在酒店等级,因为我想能够搜索一个特定的人而不搜索房间。



这个坏的设计?有另一种方式实现吗?



谢谢。

解决方案

严格来说,可以通过使用接口(抽象类,如果你的语言是例如C ++或Python)来解决这个类中的问题 IRoom IPerson ;在伪代码中

 界面IPerson 
IRoom getRoom()
// etc

接口IRoom
iter< IPerson> iterPerson()
// etc

这只会使接口彼此相互依赖 - 接口的实际实现只需要依赖于接口。



这也给了你足够的余地在实现方面,如果您希望避免循环引用循环(这可能是一个麻烦,例如在CPython中通过减缓垃圾收集) - 您可以使用弱引用,一个基础关系数据库,具有典型的一对多关系表等等。对于第一个简单的原型,您可以使用所选语言中最简单的(可能是简单的,并且通常必须是循环的,引用[[C ++中的指针]]和个人指向房间房间列表< Person> )。


I am learning a lot about design patterns when I am building my own system for my projects. And I want to ask you about a design question that I can't find an answer to.

Currently I am building a little Chat-server using sockets, with multiple Clients. Right now I have three classes:

  1. Person-class which holds information like nick, age and a Room-object.
  2. Room-class which holds information like room-name, topic and a list of Persons currently in that room.
  3. Hotel-class which have a list of Persons and a list of Rooms on the server.

I have made a diagram to illustrate it:

I have a list of persons on the server in the Hotel-class because it would be nice to keep track of how many there are online right now (Without having to iterate through all of the rooms). The persons live in the Hotel-class because I would like to be able to search for a specific Person without searching the rooms.

Is this bad design? Is there another way of achieve it?

Thanks.

解决方案

The mutual dependency problem among the classes, strictly speaking, can be solved by using interfaces (abstract classes, if your language is e.g. C++ or Python) IRoom and IPerson; in pseudocode

interface IPerson
    IRoom getRoom()
    // etc

interface IRoom
    iter<IPerson> iterPerson()
    // etc

this makes only the interfaces mutually dependent on each other -- the actual implementations of the interfaces need only depend on the interfaces.

This also gives you plenty of leeway in terms of implementation, if you want avoid circular reference loops (which can be a bother e.g. in CPython by slowing down garbage collections) -- you could use weak references, an underlying relational database with a typical "one to many relationship" table, etc, etc. And for the first simple prototype you can use what's simplest in your chosen language (probably simple, and alas necessarily circular, references [[pointers, in C++]] with a Person referring to a Room and a Room to a list<Person>).

这篇关于两个相互依赖的对象。那不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆