简单工厂模式

[实验任务]:女娲造人

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

 

类图

 

 Man类

public class Man extends Person
{

    @Override
    public void createPerson()
    {
        System.out.println("Nvwa造了一个Man");
    }
}

Woman类

public class Woman extends Person
{
    @Override
    public void createPerson()
    {
        System.out.println("Nvwa造了个Woman");
    }
}

Person抽象类

public abstract class Person
{
    public abstract void createPerson();
}

PersonFactory类

public 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;
    }
}

Robot类

public class Robot extends Person
{
    @Override
    public void createPerson()
    {
        System.out.println("Nvwa造了个Robot");
    }
}

SimpleFactory类

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造不出来");
        }
    }
}

运行结果:

 

posted @ 2023-11-06 22:55  Men!  阅读(6)  评论(0编辑  收藏  举报