每日总结

 

 

实验2:简单工厂模式

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

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

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

 

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

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

实验要求:

1. 画出对应的类图;

 

2. 提交源代码;

package factory;

 

 class Man extends Person

{

 

    @Override

    public void createPerson()

    {

        System.out.println("Nvwa造了一个Man");

    }

}

 

 

 abstract class Person

{

    public abstract void createPerson();

}

 

 

 class PersonFactory

{

    public static Person create(String type)

    {

        Person person = null;

        switch (type)

        {

            case "M":

                person = new Man();

                break;

            case "W":

                person = new Woman();

                break;

            case "R":

                person = new Robot();

                break;

            default:

                break;

        }

        return person;

    }

}

 

 

 

 class Robot extends Person

{

    @Override

    public void createPerson()

    {

        System.out.println("Nvwa造了个Robot");

    }

}

 

 

public class SimpleFactory

{

    public static void main(String[] args)

    {

        try

        {

            //Man

            Person personM = PersonFactory.create("M");

            personM.createPerson();

 

            //Woman

            Person personW = PersonFactory.create("W");

            personW.createPerson();

 

            //Robot

            Person personR = PersonFactory.create("R");

            personR.createPerson();

 

            //其他

            Person personN = PersonFactory.create("N");

            personN.createPerson();

        }

        catch (Exception e)

        {

            System.out.println("这个Nvwa造不出来");

        }

    }

}

 

  class Woman extends Person

{

    @Override

    public void createPerson()

    {

        System.out.println("Nvwa造了个Woman");

    }

}

 

3. 注意编程规范。

 

posted @ 2024-10-17 00:48  *太¥^白%  阅读(6)  评论(0)    收藏  举报