public class Test {
public static void main(String[] args){
try{
Factory.factory("A").doSth();
Factory.factory("B").doSth();
Factory.factory("C").doSth();
}catch(BadProductException e){
e.printStackTrace();
}
}
}
class Factory{
public static Product factory(String product) throws BadProductException{
if(product.equals("A"))
return new ConcreteProductA();
else if(product.equals("B"))
return new ConcreteProductB();
else
throw new BadProductException("产品标识有误!");
}
}
interface Product{
void doSth();
}
class ConcreteProductA implements Product{
@Override
public void doSth() {
System.out.println("ConcreteProductA.doSth()");
}
}
class ConcreteProductB implements Product{
@Override
public void doSth() {
System.out.println("ConcreteProductB.doSth()");
}
}
class BadProductException extends Exception{
public BadProductException(String msg){
super(msg);
}
}