Java 静态工厂Demo
接口Car.java
/* * package factory; */ public interface Car { public abstract void start(); }
实现类Pickup.java
/* * package factory; */ public class Pickup implements Car { public void start() { System.out.println("Pickup start!"); } }
实现类Mini.java
/* * package factory; */ public class Mini implements Car { @Override public void start() { System.out.println("Mini Car start!"); } }
工厂类CarFactory.java
/* * package factory; */ public class CarFactory { private static Car car = null; public static Car getCar(String type) { if ("Pickup".equalsIgnoreCase(type)) { car = new Pickup(); } if ("Mini".equalsIgnoreCase(type)) { car = new Mini(); } return car; } }
属性文件cars.properties
Mini = factory.Mini
Pickup = factory.Pickup
使用属性文件的工厂类CarFactoryWithProperties.java
/* * package factory; */ public class CarFactoryWithProperties { private static Car car = null; public static Properties properties = new Properties(); public static Car getCar(String type) throws IOException, InstantiationException, ClassNotFoundException, IllegalAccessException { InputStream inStream = null; inStream = new FileInputStream("src/factory/cars.properties"); properties.load(inStream); String carClass = properties.getProperty(type); car = (Car) Class.forName(carClass).newInstance(); return car; } }
测试类Test.java
/* * package factory; */ public class Test { public static void main(String[] args) throws IOException, InstantiationException, ClassNotFoundException, IllegalAccessException { CarFactory.getCar("mini").start(); CarFactory.getCar("Pickup").start(); System.out.println("-----------------------------"); CarFactoryWithProperties.getCar("Mini").start(); //CarFactoryWithProperties.getCar("mini").start(); } }
运行结果:
run: Mini Car start! Pickup start! ----------------------------- Mini Car start! 成功构建 (总时间: 0 秒)