【java设计模式】【创建模式Creational Pattern】简单工厂模式Simple Factory Pattern(静态工厂方法模式Static Factory Method Pattern)

 1 public class Test {
 2     public static void main(String[] args){
 3         try{
 4             Factory.factory("A").doSth();
 5             Factory.factory("B").doSth();
 6             Factory.factory("C").doSth();
 7         }catch(BadProductException e){
 8             e.printStackTrace();
 9         }
10         
11     }
12 }
13 class Factory{
14     public static Product factory(String product) throws BadProductException{
15         if(product.equals("A"))
16             return new ConcreteProductA();
17         else if(product.equals("B"))
18             return new ConcreteProductB();
19         else 
20             throw new BadProductException("产品标识有误!");
21     }
22 }
23 interface Product{
24     void doSth();
25 }
26 class ConcreteProductA implements Product{
27     @Override
28     public void doSth() {
29         System.out.println("ConcreteProductA.doSth()");
30     }
31 }
32 class ConcreteProductB implements Product{
33     @Override
34     public void doSth() {
35         System.out.println("ConcreteProductB.doSth()");
36     }
37 }
38 class BadProductException extends Exception{
39     public BadProductException(String msg){
40         super(msg);
41     }
42 }
原文地址:https://www.cnblogs.com/xiongjiawei/p/6835506.html