简单工厂Factory
程序员文章站
2022-04-25 12:32:20
...
package net.util; /** * @项目名:spring2.5 * @包名:net.util * @文件名:FactoryDemo.java * @日期:Jun 21, 2011 4:37:02 PM * @备注:工厂模式 * @作者:apple */ public class FactoryDemo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Car c=Factory.getCarInstance("Banz"); if(c!=null){ c.run(); c.stop(); } else{ System.out.println("制造不了"); } } } class Factory{ public static Car getCarInstance(String type){ Car c=null; try { c=(Car)Class.forName("net.util."+type).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return c; } } interface Car{ public void run(); public void stop(); } class Banz implements Car{ public void run() { // TODO Auto-generated method stub System.out.println("Banz跑"); } public void stop() { // TODO Auto-generated method stub System.out.println("Banz停"); } } class Ford implements Car{ public void run() { // TODO Auto-generated method stub System.out.println("Ford跑"); } public void stop() { // TODO Auto-generated method stub System.out.println("Ford停"); } }