假设一个问题
现有一个接口,和两个继承接口的类
interface Ifood{
public void eat();
}
class Bread implements Ifood{
public void eat() {
System.out.println("在吃面包");
}
}
class Mike implements Ifood{
public void eat() {
System.out.println("在喝牛奶");
}
}
若想要实现输出“在吃面包”的功能,可以这样编写主类
public class Demo3{
public static void main(String[] args) {
Ifood food = new Bread();
food.eat();
}
}
如果现在想要输出“在喝牛奶”,就要修改代码,如果又想要干其他的又得继续修改,这样的代码不符合我们的预期,不够省事。
采用工厂设计模式
interface Ifood{
public void eat();
}
class Bread implements Ifood{
public void eat() {
System.out.println("在吃面包");
}
}
class Mike implements Ifood{
public void eat() {
System.out.println("在喝牛奶");
}
}
class Factory{
public static Ifood newClass(String ClassName) {
if("bread".equals(ClassName)) {
return new Bread();
}
else if("Mike".equals(ClassName)) {
return new Mike();
}
return null;
}
}
public class Demo3{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Ifood food = Factory.newClass(in.nextLine());
food.eat();
}
}
这里多增加了一个 Factory 类,用它来接收输入,对输入进行判断看到底要new哪个对象,不再需要反复修改代码