1.问题描述
本人开了一家工厂,专门生产女士皮包,女士皮包的种类很多有小方包,妈妈包、信封包等,智能时代到来了,我现在要用代码生产这几种包包了。
2.开始写代码
1. 原始代码
package com.sumei.pattern.simplefactory; /** * 工厂女包api */ public interface FemaleBag { String ProcessingBag(); }
package com.sumei.pattern.simplefactory; /** * 信封包 */ public class Envelopes implements FemaleBag { @Override public String ProcessingBag() { return "信封包"; } }
package com.sumei.pattern.simplefactory; /** * 子母包 */ public class MotherBag implements FemaleBag { @Override public String ProcessingBag() { return "妈妈包"; } }
2.客户端代码
package com.sumei.pattern.simplefactory; public class Client { public static void main(String[] args) { FemaleBag femaleBag=new Envelopes(); System.out.println("我要得到包是:"+femaleBag.ProcessingBag()); } }
客户端在调用我工厂的时候,客户端不但知道了我的接口,还知道了我是怎么生产的,这个商业机密怎么能给别人看呢。接口的作用是“封装隔离”,但我怎么没看出来呢,然后进行代码改造
3.用简单工厂进行改造
package com.sumei.pattern.simplefactory; /** * 生产包包的工厂 */ public class BagFactory { public static FemaleBag createBag(int flag){ FemaleBag femaleBag=null; if(flag==1){ femaleBag=new Envelopes(); }else if (flag==2){ femaleBag=new MotherBag(); } return femaleBag; } }
4.简单工厂模式的客户端调用
public static void main(String[] args) { FemaleBag bag = BagFactory.createBag(2); System.out.println(bag.ProcessingBag()); }
5.用配置文件+反射去掉判断
从上个方法我们可以看见,客户端不知道包包是怎么生产出来的,这下安全了。但是随着业务的增加,我开发出了一个新的包包。发现没增加一个包我就需要添加一个else if ,太痛苦了
这下可咋办呢,用反射生成吧,实验下,看看可以不
新加个类
package com.sumei.pattern.simplefactory; /** * 水桶包 */ public class BucketBag implements FemaleBag { @Override public String ProcessingBag() { return "水桶包"; } }
新建个Factory.properties配置文件
文件内容
MotherBag=com.sumei.pattern.simplefactory.MotherBag FemaleBag=com.sumei.pattern.simplefactory.BucketBag Envelopes=com.sumei.pattern.simplefactory.Envelopes
修改简单工厂类
package com.sumei.pattern.simplefactory; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class BagFactoryTwo { public static FemaleBag createBag(String bagName){ Properties properties=new Properties(); InputStream inputStream=null; inputStream=BagFactory.class.getResourceAsStream("Factory.properties"); try { properties.load(inputStream); } catch (IOException e) { e.printStackTrace(); System.out.println("装载异常"); }finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } FemaleBag femaleBag=null; try { System.out.println(properties.getProperty("BagClass")); femaleBag= (FemaleBag) Class.forName(properties.getProperty(bagName)).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return femaleBag; } }
新建一个类,只要配置Factory.properties文件就可以,不用修改代码。哎本人是个穷小子,只能建个简单工程,建其他工厂还要投资啊。
客户端调用
public static void main(String[] args) { FemaleBag motherBag = BagFactoryTwo.createBag("MotherBag"); System.out.println(motherBag.ProcessingBag()); }