java中的factory模式是什么 怎么运用的

2024-11-27 22:39:48
推荐回答(1个)
回答(1):

用接口或父类接受工厂类返回的子类相应的对象
Exp:
Father.java:
abstract public class Father {

abstract public void shout();
}
Daughter.java:
public class Daughter extends Father {

public void shout() {
System.out.println("shout from Daughter");
}
}
Son.java:
public class Son extends Father {

public void shout() {
System.out.println("shout from Son");
}
}
Factory.java:
public class Factory {

public static Father getFatherInstance() {
return new Daughter();
//return new Son();
}
}
Test.java:
public class Test {

public static void main(String[] args) {
Father father = Factory.getFatherInstance();
father.shout();
}
}
在真正使用中,只对父类有接触,并不接触真正的实例..
这是最简单的工厂模式