实验2:简单工厂模式

实验2:简单工厂模式

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

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

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

 
   

 


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

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

1.

 

 

 

2.

抽象产品类(造人类):

package SimpleFactoryPattern;

public abstract class Gj19Person {

    public void run(){}

    public void eat(){}

}

具体产品类(男人类):

package SimpleFactoryPattern;

public class Gj19Man extends Gj19Person{

    public void eat() {

        System.out.println("男人吃东西..");

        super.eat();

    }

    public void run() {

        System.out.println("男人跑步..");

        super.run();

    }

}

具体产品类(女人类):

package SimpleFactoryPattern;

public class Gj19Woman extends Gj19Person{

    public void eat() {

        System.out.println("女人吃东西..");

        super.eat();

    }

    public void run() {

        System.out.println("女 人跑步..");

        super.run();

    }

}

具体产品类(机器人类):

      package SimpleFactoryPattern;

public class Gj19Robot extends Gj19Person{

    public void eat() {

        System.out.println("机器人吃东西..");

        super.eat();

    }

    public void run() {

        System.out.println("机器人跑步..");

        super.run();

    }

}

工厂类(女娲类):

package SimpleFactoryPattern;

public class Gj19Nvwa {

    public static Gj19Person getPerson(String people){

        Gj19Person gj19Person=null;

        if(people.equalsIgnoreCase("M")){

            gj19Person = new Gj19Man();

        }else if(people.equalsIgnoreCase("W")){

            gj19Person = new Gj19Woman();

        }else if(people.equalsIgnoreCase("R")){

            gj19Person = new Gj19Robot();

        }

        return gj19Person;

    }

}

女娲造人测试:

package SimpleFactoryPattern;

public class Gj19NvwaMakePerson {

    public static void main(String[] args) {

        Gj19Person gj19Person;

        gj19Person = Gj19Nvwa.getPerson("M");  //女娲造男人

        gj19Person.eat(); 

        gj19Person = Gj19Nvwa.getPerson("W"); //女娲造女人

        gj19Person.eat(); 

        gj19Person = Gj19Nvwa.getPerson("R"); //女娲造机器人

        gj19Person.eat(); 

    }

}

运行截图:

 

 

 

 

posted @ 2022-10-17 21:26  萧贾jzm  阅读(50)  评论(0编辑  收藏  举报
//歌单id