问题描述
- 菜鸟饼 能不能用java的工厂模式处理下面的问题。 求代码 和 注释
-
interface Animal{ public void say(); } class Mammal implements Animal{ public void say(){ System.out.println("哺乳动物"); } } class Reptiles implements Animal{ public void say(){ System.out.println("爬行动物"); } } class Whale implements Animal{ private Animal animal; public Whale(Animal animal){ this.animal = animal; } public void say(){ System.out.println("鲸喷水"); animal.say(); } } class Dog implements Animal{ private Animal animal; public Dog(Animal animal){ this.animal = animal; } public void say(){ System.out.println("狗汪汪叫"); animal.say(); } } class Lizards implements Animal{ private Animal animal; public Lizards(Animal animal){ this.animal = animal; } public void say(){ System.out.println("蜥蜴四角爬行"); animal.say(); } } class Snake implements Animal{ private Animal animal; public Snake(Animal animal){ this.animal = animal; } public void say(){ System.out.println("蛇有毒"); } } class Gecko implements Animal{ private Animal lizards; public Gecko(Animal lizards){ this.lizards = lizards; } public void say(){ System.out.println("壁虎是蜥蜴的一种,它比较小"); lizards.say(); } } class MonitorLizard implements Animal{ private Animal animal; public MonitorLizard(Animal animal){ this.animal = animal; } public void say(){ System.out.println("巨蜥是蜥蜴的一种,它比较大"); animal.say(); } } class Test{ public static void main(String args []){ int flag = 4; if(flag == 1){ Mammal mammal = new Mammal(); Whale whale = new Whale(mammal); whale.say(); } else if(flag == 2){ Reptiles reptiles = new Reptiles(); Lizards lizards = new Lizards(reptiles); lizards.say(); } else if(flag == 3){ Reptiles reptiles1 = new Reptiles(); Lizards lizards1 = new Lizards(reptiles1); Gecko gecko1 = new Gecko(lizards1); gecko1.say(); } else if(flag == 4){ Reptiles reptiles2 = new Reptiles(); Lizards lizards2 = new Lizards(reptiles2); MonitorLizard ml = new MonitorLizard(lizards2); ml.say(); } } }
解决方案
修改下你的Test类,提取成一个工厂类,面向抽象编程的原则,根据传入的type类型返回具体的某个实现类。
参考代码如下:
class AnimalFactory {
public static Animal factory(int type) {
Animal instance = null;
switch (type) {
case 1:
Mammal mammal = new Mammal();
instance = new Whale(mammal);
break;
case 2:
Reptiles reptiles = new Reptiles();
instance = new Lizards(reptiles);
break;
case 3:
Reptiles reptiles1 = new Reptiles();
Lizards lizards1 = new Lizards(reptiles1);
instance = new Gecko(lizards1);
break;
case 4:
Reptiles reptiles2 = new Reptiles();
Lizards lizards2 = new Lizards(reptiles2);
instance = new MonitorLizard(lizards2);
break;
default:
System.out.println("not support this type.");
}
return instance;
}
public static void main(String[] args) {
int flag = 4;
Animal animal = AnimalFactory.factory(flag);
if (animal != null) {
animal.say();
} else {
System.out.println("this type is not supported.");
}
}
}
测试结果跟你的main方法一样,就是将你的main方法中new子类的过程作为工厂方法提出来,根据传入的类型来创建子类,最终返回的类型是抽象类。
解决方案二:
可以是可以,但是没必要。你的main提出出来,把 flag 作为参数,就是“简单工厂模式”。
解决方案三:
可以用抽象工厂模式!
时间: 2024-09-22 18:20:50