欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式之工厂方法模式

程序员文章站 2024-01-05 17:14:28
...
  1. 工厂方法模式

  • 结构
    抽象工厂Factory + 具体工厂ConcreteFactory + 抽象产品Product + 具体产品ConcreteProduct
  • 适用环境
    客户端不知道它所需要的对象的类,抽象工厂类通过其子类来指定创建哪个对象。
  • 实现
public interface Factory {
   public Product createProduct();
}
public class ProductAFactory implements Factory {
   @Override
   public Product createProduct() {
       System.out.println("产品A初始化");
       Product product = new ProductA();
       return product;
   }
}
public class ProductBFactory implements Factory {
   @Override
   public Product createProduct() {
       System.out.println("产品B初始化");
       Product product = new ProductB();
       return product;
   }
}
public interface Product {
   public void productDetaile();
}
public class ProductA implements Product{
   @Override
   public void productDetaile() {
       System.out.println("产品A详情");
   }
}
public class ProductB implements Product {
   @Override
   public void productDetaile() {
       System.out.println("产品B详情");
   }
}
public class Client {
   public static void main(String[] args) {
       Factory factory;
       Product product;
       factory = (Factory)XMLUtils.getBean();
       product = factory.createProduct();
       product.productDetaile();
   }
}
控制台输出:
产品B初始化
产品B详情
//该方法用于从XML配置文件中提取类的类名,并返回实例对象
   public static Object getBean(){
       try {
           DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = dFactory.newDocumentBuilder();
           Document doc;
           doc = builder.parse(new File("resources//createPattern//factoryMethod//config.xml"));

           NodeList nodeList = doc.getElementsByTagName("className");
           Node firstChild = nodeList.item(0).getFirstChild();
           String className = firstChild.getNodeValue().trim();

           Class c = Class.forName(className);
           Object object = c.newInstance();
           return object;
       }catch (Exception e){
           e.printStackTrace();
           return null;
       }
   }
<?xml version="1.0" encoding="UTF-8"?>
<config>
   <className>createPattern.factoryMethod.ProductBFactory</className>
</config>