本文将用反射机制和配置文件改进抽象工厂。
抽象工厂示例
结构如下所示:
AbstractComputer,AbstractDisplay相似,他们都为抽象产品类。
public class AbstractComputer { protected String manufacturerName=""; protected String modelName=""; public String showDetails(){ return "生产商为 "+manufacturerName+"型号为 "+modelName; } }
AppleComputer,DellComputer类继承了AbstractComputer,实现具体的产品。对于显示器类型的抽象产品与具体产品的关系相似,代码如下:
public class AppleComputer extends AbstractComputer{ protected String manufacturerName="APPLE"; protected String modelName="Q1"; public String showDetails(){ return "生产商为 "+manufacturerName+"型号为 "+modelName; } }
DeviceFactory为抽象工厂类,包含多个创建产品的方法,可以创建Computer等不同类型族的产品。
public abstract class DeviceFactory { // 创造一台电脑 abstract public AbstractComputer CreateComputer(); // 创造一台显示器 abstract public AbstractDisplay CreateDisplay(); }
AppleFactory继承了DeviceFactory,实现抽象工厂中的多个抽象方法,完成具体产品的创建。DellFactory相似。
public class AppleFactory extends DeviceFactory { public AbstractComputer CreateComputer(){ return new AppleComputer(); } public AbstractDisplay CreateDisplay(){ return new AppleDisplay(); } }
Test客户端
public class Test { public static void main(String[] args) { AbstractComputer myPC; AbstractDisplay myDisplay; DeviceFactory factory=new DellFactory(); // DeviceFactory factory=new AppleFactory(); myPC=factory.CreateComputer(); myDisplay=factory.CreateDisplay(); System.out.println("电脑:"+myPC.showDetails()); System.out.println("显示器:"+myDisplay.showDetails()); } }
uml如图所示:
接下来使用反射机制加配置文件改进该抽象工厂示例。
结构中引入配置文件,删去所有的工厂,只留下DeviceFactory,其他类保持不变。
配置文件Device.properties
#DeviceComputer=AppleComputer #DeviceDisplay=AppleDisplay DeviceComputer=DellComputer DeviceDisplay=DellDisplay
工厂DeviceFactory
public class DeviceFactory { public static Properties properties = new Properties(); public static File file = new File("src\\Device.properties"); public static AbstractComputer CreateComputer() throws Exception{ properties.load(new FileInputStream(file)); return (AbstractComputer)Class.forName(properties.getProperty("DeviceComputer")).newInstance(); }; public static AbstractDisplay CreateDisplay() throws Exception{ return (AbstractDisplay)Class.forName(properties.getProperty("DeviceDisplay")).newInstance(); }; }
Test客户端
public class Test { public static void main(String[] args) throws Exception { AbstractComputer myPC; AbstractDisplay myDisplay; myPC=DeviceFactory.CreateComputer(); myDisplay=DeviceFactory.CreateDisplay(); System.out.println("电脑:"+myPC.showDetails()); System.out.println("显示器:"+myDisplay.showDetails()); } }
uml类图: