设计模式练习(1)——简单工厂模式
·
简单工厂模式
一、题目:
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W。则返回一个对象Woman,用java语言实现该场景。现在需要增加一个新的Robot类,如果传入参数R,则返回一个Robot对象,对代码进行修改并注意女娲的变化。
(1)绘制简单工厂模式结构视图;
(2)请绘制该实例类图,并代码实现。
二、所用模式结构视图:
三、实例类图:
四、实例实现代码:
(因为区分,所以在类的前面加了Gj19)
抽象产品类–造人类:
package SimpleFactoryPattern;
/**
* 抽象产品类--造人类
* @author gong
*
*/
public abstract class Gj19Person {
public void run(){}
public void eat(){}
}
具体产品类–男人类:
package SimpleFactoryPattern;
/**
* 具体产品类--男人类
* @author gong
*
*/
public class Gj19Man extends Gj19Person{
@Override
public void eat() {
System.out.println("男人吃东西..");
super.eat();
}
@Override
public void run() {
System.out.println("男人跑步..");
super.run();
}
}
具体产品类–女人类:
package SimpleFactoryPattern;
/**
* 具体产品类--女人类
* @author gong
*
*/
public class Gj19Woman extends Gj19Person{
@Override
public void eat() {
System.out.println("女人吃东西..");
super.eat();
}
@Override
public void run() {
System.out.println("女 人跑步..");
super.run();
}
}
具体产品类–机器人类:
package SimpleFactoryPattern;
/**
* 具体产品类--机器人类
* @author gong
*
*/
public class Gj19Robot extends Gj19Person{
@Override
public void eat() {
System.out.println("机器人吃东西..");
super.eat();
}
@Override
public void run() {
System.out.println("机器人跑步..");
super.run();
}
}
工厂类–女娲类:
package SimpleFactoryPattern;
/**
* 工厂类--女娲类
* @author gong
*
*/
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;
/**
* 女娲造人的测试
* @author gong
*
*/
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();
}
}
五、运行结果:
更多推荐
所有评论(0)