软件设计:实验2:简单工厂模式

实验2:简单工厂模式

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

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

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

 

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

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

 

1.

 

 

2.// 抽象类 Person

abstract class Person {

    protected String name;

    protected String gender;

 

    public Person(String name, String gender) {

        this.name = name;

        this.gender = gender;

    }

 

    public abstract void speak();

}

 

// Man 类

class Man extends Person {

    public Man(String name) {

        super(name, "Male");

    }

 

    @Override

    public void speak() {

        System.out.println(name + " says: I am a man.");

    }

}

 

// Woman 类

class Woman extends Person {

    public Woman(String name) {

        super(name, "Female");

    }

 

    @Override

    public void speak() {

        System.out.println(name + " says: I am a woman.");

    }

}

 

// Robot 类

class Robot extends Person {

    public Robot(String name) {

        super(name, "Robot");

    }

 

    @Override

    public void speak() {

        System.out.println(name + " says: I am a robot.");

    }

}

 

// 工厂类 Nvwa

class Nvwa {

    public Person createPerson(String type) {

        switch (type) {

            case "M":

                return new Man("Man");

            case "W":

                return new Woman("Woman");

            case "R":

                return new Robot("Robot");

            default:

                throw new IllegalArgumentException("Invalid type");

        }

    }

}

 

// 测试类

public class NvwaTest {

    public static void main(String[] args) {

        Nvwa nvwa = new Nvwa();

        Person person = nvwa.createPerson("M");

        person.speak();

 

        person = nvwa.createPerson("W");

        person.speak();

 

        person = nvwa.createPerson("R");

        person.speak();

    }

}

posted @ 2024-11-27 16:59  痛苦代码源  阅读(2)  评论(0编辑  收藏  举报