- 工厂模式的概念
工厂模式的作用是实例化对象,用工厂的方式来代替new操作创建对象的方式,工厂模式用来产生相似的对象 - 应用
定义一个接口来创建对象,但是让子类来决定哪些类需要被实例化。工厂方法把实例化的工作推迟到子类中去实现 - 适用场景(以下会有例子进行说明)
①一组类似的对象需要创建
②在编码时不能预见需要创建那种类的实例
③系统需要考虑扩展性,不应该依赖产品实例产生的一些细节 - 工厂模式应用举例
创建一个生产衣服的接口
package com.fgy.factory;
public interface ClothesInterface {
//生产衣服,衣服会有很多类型,男装,女装,运动装,休闲装等等
public void productClothes();
}
实现类
package com.fgy.factory;
public class ManClothes implements ClothesInterface {
@Override
public void productClothes() {
System.out.println("***************生产男装**************");
}
}
package com.fgy.factory;
public class WomanClothes implements ClothesInterface {
@Override
public void productClothes() {
System.out.println("***************生产女装**************");
}
}
测试类:
package com.fgy.factory;
public class FactoryTest {
public static void main(String[] args) {
ClothesInterface manClothes = new ManClothes();
ClothesInterface womanClothes = new WomanClothes();
manClothes.productClothes();
womanClothes.productClothes();
}
}
结果
但是这样写代码,不利于扩展和维护,所以写成如下的,先建立一个ClothesFactory类,来对衣服的种类进行统一管理,这样就不需要客户端来显示的创建衣服了,直接交给它就可以了
package com.fgy.factory;
public class ClothesFactory {
public static ClothesInterface getClothes(String key) {
if ("man".equals(key)) {
return new ManClothes();
}else if ("woman".equals(key)) {
return new WomanClothes();
}
return null;
}
}
这种方式有一个缺点,每多一种类型的衣服,就要加一个else if,很麻烦,不能智能的根据衣服的种类来自动的创建,用类的反射原理进行改进代码
package com.fgy.factory;
public class ClothesFactory {
public static ClothesInterface getClothesByClassName(String className) {
try {
ClothesInterface clothes = (ClothesInterface) Class.forName(className).newInstance();
return clothes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
工厂方法模式完事
抽象工厂模式应用举例