帮我写一段会议管理系统的会议预约部分的代码,先帮我生成不遵守单一职责原则的代码,在帮助我把他修改成遵守单一职责原则的代码,并加以说明
时间: 2024-05-07 11:18:40 浏览: 74
会议室预约系统源码
生成不遵守单一职责原则的代码:
```python
class Meeting:
def __init__(self, name, start_time, end_time, attendees):
self.name = name
self.start_time = start_time
self.end_time = end_time
self.attendees = attendees
class MeetingScheduler:
def __init__(self):
self.meetings = []
def schedule_meeting(self, meeting):
for m in self.meetings:
if m.start_time < meeting.end_time and meeting.start_time < m.end_time:
return False
self.meetings.append(meeting)
return True
```
这段代码存在的问题是,`MeetingScheduler` 类承担了过多的职责,包括会议预约、会议时间冲突检查等。这违反了单一职责原则。
修改后的代码如下:
```python
class Meeting:
def __init__(self, name, start_time, end_time, attendees):
self.name = name
self.start_time = start_time
self.end_time = end_time
self.attendees = attendees
class MeetingConflictChecker:
def __init__(self, meetings):
self.meetings = meetings
def check_conflict(self, meeting):
for m in self.meetings:
if m.start_time < meeting.end_time and meeting.start_time < m.end_time:
return False
return True
class MeetingScheduler:
def __init__(self):
self.meetings = []
def schedule_meeting(self, meeting):
conflict_checker = MeetingConflictChecker(self.meetings)
if conflict_checker.check_conflict(meeting):
self.meetings.append(meeting)
return True
else:
return False
```
修改后的代码将会议时间冲突检查的职责分离出来,并将其封装到了一个新的类 `MeetingConflictChecker` 中。`MeetingScheduler` 类仅负责会议预约的职责,更符合单一职责原则。
需要注意的是,这只是一个简单的例子,实际情况中可能需要更细粒度的职责划分。在实际开发中,应该根据具体需求来划分职责。
阅读全文