62,623
社区成员
发帖
与我相关
我的任务
分享public interface A {
public String print();
}
public class A1 implements A {
public String print() {
System.out.println("I am the first child of A.");
}
}
public class A2 implements A {
public String print() {
System.out.println("I am the second child of A.");
}
}
public class Factory {
private Factory(){}
// 静态工厂方法
public static A getAChild(String name) {
if(name.equalsIgnoreCase("a1")) {
return new A1();
}else if(name.equalsIgnoreCase("a2")) {
return new A2();
}
return null;
}
}
public class Test {
public static void main(String[] args) {
A child1 = Factory.getAChild("a1");
child.print();
A child2 = Factory.getAChild("a2");
child.print();
}
}