工厂模式:通过子类决定创建的对象是什么,来达到对对象创建过程封装的目的。
这里我们举一个简单的例子:
玩具工厂根据所传的参数类型,判断创建何种玩具。
缺点:
1.有较多的判断。
2.如果要添加更多的类型,必须重改这个创建的方法。
3.耦合度高。
将Toy变成接口类,让各个角色的玩具实现这个接口类。它具有玩具的所有公有方法,这样提高了系统的灵活性。
public interface Toy {
public void make();
}
//实现类:
public class Cat implements Toy{
@Override
public void make() {
System.out.println("制作小猫....");
}
}
public class Dog implements Toy{
@Override
public void make() {
System.out.println("制作小狗.....");
}
}
public class ToyFactory {
public static Toy createToy(String type){
Toy toy=null;
if(type.equals("cat")){
toy= new Cat();
}else if(type.equals("bear")){
toy=new Bear();
}else if(type.equals("dog")){
toy=new Dog();
}
return toy;
}
}
缺点:如果我们添加玩具的类型的时候,还是要更改这个工厂代码。
现在,我们不再根据玩具工厂来统一创建玩具,根据不同类型的玩具给出不同的工厂。
public interface ToyFactory {
public Toy createToy();
}
public class CatFactory implements ToyFactory {
@Override
public Toy createToy() {
Cat cat=new Cat();
cat.make();
return cat;
}
}
public class DogFactory implements ToyFactory {
@Override
public Toy createToy() {
Dog dog=new Dog();
dog.make();
return dog;
}
}
public class BearFactory implements ToyFactory{
@Override
public Toy createToy() {
Bear bear=new Bear();
bear.make();
return bear;
}
}
现在我们通过反射和解析XML来创建你想要创建的玩具
<factory>
<className>BearFactory</className>
</factory>
XMLUtil来解析这个文件:
public class XMLUtil {
public static Object getBean()throws Exception{
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
Document document= documentBuilder.parse("config.xml");
NodeList nodeList=document.getElementsByTagName("className");
org.w3c.dom.Node classNode = nodeList.item(0).getFirstChild();
String className=classNode.getNodeValue();
//这里的"Creational.Factory."是包名
String s="Creational.Factory."+className;
Class c=Class.forName(s);
Object o=c.newInstance();
return o;
}
}
/*
测试类
*/
public class TestFactory {
public static void main(String[] args) {
try {
ToyFactory toyFactory=(ToyFactory) XMLUtil.getBean();
toyFactory.createToy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
我们可以通过更改xml的文件,来创建我们想创建的玩具。
工厂模式的优点:
1.我们可以隐藏创建玩具的过程。用户无需关心。
2. 想要更改想要的产品,无需更改内部代码。