下面是我面试的时候遇到的一道面试题,题目是使用java代码实现简单的工厂模式
package test;
class A{
publicvoid print(){
}
}
class B extends A{
publicvoid print(){
System.out.println("b");
}
}
class C extends A{
publicvoid print(){
System.out.println("c");
}
}
class Factory {
publicstatic A instance(String name){
Aobj=null;
if("b".equals(name)){
obj=newB();
}elseif("c".equals(name)){
obj=newC();
}else{
thrownew RuntimeException("你的输入有误!");
}
returnobj;
}
}
|