9.27

实验2:简单工厂模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解简单工厂模式的动机,掌握该模式的结构;

2、能够利用简单工厂模式解决实际问题

 

[实验任务一]:女娲造人

使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。

实验要求:

1. 画出对应的类图;

 

 

 

2. 提交源代码;

class Person:
    def introduce(self):
        pass

class Man(Person):
    def introduce(self):
        return "I am a Man."

class Woman(Person):
    def introduce(self):
        return "I am a Woman."

class Robot(Person):
    def introduce(self):
        return "I am a Robot."

class PersonFactory:
    @staticmethod
    def create_person(person_type):
        if person_type == 'M':
            return Man()
        elif person_type == 'W':
            return Woman()
        elif person_type == 'R':
            return Robot()
        else:
            raise ValueError("Unknown person type")

# 测试代码
if __name__ == "__main__":
    person_type = input("输入创造的人 (M/W/R): ")
    try:
        person = PersonFactory.create_person(person_type)
        print(person.introduce())
    except ValueError as e:
        print(e)

 

3.注意编程规范。

posted @ 2024-11-27 08:14  The-rich  阅读(11)  评论(0)    收藏  举报