一、简单工厂
package com.xu.demo.factoryPattern;/*** 简单工厂模式类*/
public class SimpleFactoryPattern {public static Phone create(String name) {//根据输入对象名称判断返回相匹配的对象if("IPhone".equals(name)) {//返回对象return new IPhone();}else if("MiPhone".equals(name)) {return new MiPhone();}return null;}public static void main(String[] args) {Phone phone = SimpleFactoryPattern.create("IPhone");phone.call();Phone phone2 = SimpleFactoryPattern.create("MiPhone");phone2.call();}
}
二、普通工厂
1、Phone接口
package com.xu.demo.factoryPattern;/*** 抽象电话的接口*/
public interface Phone {/*** 抽象的打电话的功能,有不同的实现类做具体的实现*/void call();
}
2、PhoneFactory接口
package com.xu.demo.factoryPattern;public interface PhoneFactory {/*** 抽象的创建方法* @return*/Phone create();
}
3、IPhone类
package com.xu.demo.factoryPattern;public class IPhone implements Phone{@Overridepublic void call() {System.out.println("我在使用IPhone给你打电话!");}
}
4、MiPhone类
package com.xu.demo.factoryPattern;public class MiPhone implements Phone{@Overridepublic void call() {System.out.println("我在使用小米手机给你打电话!");}
}
5、IPhoneFactory类
package com.xu.demo.factoryPattern;/*** 苹果手机工厂*/
public class IPhoneFactory implements PhoneFactory {@Overridepublic Phone create() {return new IPhone();}
}
6、MiPhoneFactory类
package com.xu.demo.factoryPattern;/*** 小米手机工厂*/
public class MiPhoneFactory implements PhoneFactory {@Overridepublic Phone create() {return new MiPhone();}
}
7、FactoryPattern类
三、超级工厂
package com.xu.demo.factoryPattern;import java.lang.reflect.InvocationTargetException;/***** 超级工厂(简单工厂 + 反射 + 泛型),利用反射机制解决开闭原则的问题*/
public class SuperFactory {public static void main(String[] args) {//com.lx.dom.impl.pro这一段是包名,IPhone是类名,不能输错Phone phone = SuperFactory.create("com.xu.demo.factoryPattern.MiPhone") ;phone.call();}/*** 根据完整类型名动态加载class并创建实例* @param className* @return*/@SuppressWarnings("unchecked")public static <T> T create(String className) {try {//动态加载classClass<?> clazz = Class.forName(className);//通过calss对象获取构造函数创建新实例return (T) clazz.getConstructor().newInstance();} catch (Exception e) {//异地重抛throw new RuntimeException("Create instance fail.",e);}}}
运行结果: