建造者模式uml学生教师
时间: 2024-01-22 18:15:07 浏览: 60
建造者模式是一种创建型设计模式,它允许我们逐步创建复杂对象。在建造者模式中,我们可以将一个复杂对象的构建过程与其表示分离开来,以便同样的构建过程可以创建不同的表示。在学生和教师的例子中,我们可以使用建造者模式来创建一个学校对象,该对象包含多个教师和学生。以下是建造者模式的UML类图:
```
+--+
| School |
+--+
| -teachers: list |
| -students: list |
+--+
/\
|
|
+--+
| SchoolBuilder |
+--+
| +buildTeachers()|
| +buildStudents()|
| +getSchool() |
+--+
/\
|
|
+--+
| Director |
+--+
| -builder: SchoolBuilder |
+--+
| +constructSchool() |
+--+
/\
|
|
+--+
| Person |
+--+
| -name: string |
| -age: int |
+--+
/\
|
|
+--+
| Teacher |
+--+
| -subject: string|
+--+
/\
|
|
+--+
| Student |
+--+
| -grade: int |
+--+
```
在上面的UML类图中,School类是我们要创建的复杂对象,它包含多个教师和学生。SchoolBuilder类是一个抽象建造者,它定义了创建School对象所需的方法。Director类是一个构建指挥者,它使用SchoolBuilder来构建School对象。Person类是一个基类,它定义了所有人员的共同属性。Teacher类和Student类是Person类的子类,它们分别定义了教师和学生的特定属性。
以下是一个使用建造者模式创建School对象的示例代码:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
class School:
def __init__(self):
self.teachers = []
self.students = []
def add_teacher(self, teacher):
self.teachers.append(teacher)
def add_student(self, student):
self.students.append(student)
class SchoolBuilder:
def build_teachers(self):
pass
def build_students(self):
pass
def get_school(self):
pass
class MySchoolBuilder(SchoolBuilder):
def __init__(self):
self.school = School()
def build_teachers(self):
self.school.add_teacher(Teacher("Mr. Smith", 35, "Math"))
self.school.add_teacher(Teacher("Mrs. Johnson", 40, "English"))
def build_students(self):
self.school.add_student(Student("John", 15, 9))
self.school.add_student(Student("Jane", 14, 8))
def get_school(self):
return self.school
class Director:
def __init__(self, builder):
self.builder = builder
def construct_school(self):
self.builder.build_teachers()
self.builder.build_students()
builder = MySchoolBuilder()
director = Director(builder)
director.construct_school()
school = builder.get_school()
```
阅读全文