用接口或父类接受工厂类返回的子类相应的对象
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(); //由Factory类决定该行代码的结果,つもり、只修改Factory类就会产生不同结果。
}
}
在真正使用中,只对父类有接触,并不接触真正的实例..
这是最简单的工厂模式
阅读(1704) | 评论(0) | 转发(0) |