設計模式之----工廠模式
阿新 • • 發佈:2018-11-05
工廠模式
有一個OEM製造商代理做HP膝上型電腦(Laptop),後來該製造商得到了更多的品牌膝上型電腦的訂單Acer,Lenovo,Dell,該OEM商發現,如果一次同時做很多個牌子的本本,有些不利於管理。利用工廠模式改善設計,用Java控制檯應用程式實現該OEM製造商的工廠模式。繪製該模式的UML圖。可更改的部分要求用XML配置檔案實現。
(此圖引用自qq_35853)
注意此UML與下面程式碼不對應,貼出來是為了更容易理解
package laptop;
//電腦品牌型別
public interface Laptop {
public void laptopType ();
}
package laptop;
//Acer
public class Acer implements Laptop {
@Override
public void laptopType() {
System.out.println("Acer");
}
}
package laptop;
//Dell
public class Dell implements Laptop{
@Override
public void laptopType() {
System.out.println("Dell");
}
}
package laptop;
//Lenovo
public class Lenovo implements Laptop{
@Override
public void laptopType() {
System.out.println("Lenovo");
}
}
package laptop;
//電腦品牌型別工廠實體類
public interface LaptopFactory {
Laptop getLaptopType();
}
class AcerFactory implements LaptopFactory{
@Override
public Laptop getLaptopType() {
return ( Acer)BeanFactory.getBean("AcerDao");
}
}
class LenovoFactory implements LaptopFactory{
@Override
public Laptop getLaptopType() {
return (Lenovo)BeanFactory.getBean("LenovoDao");
}
}
class DellFactory implements LaptopFactory{
@Override
public Laptop getLaptopType() {
return (Dell)BeanFactory.getBean("DellDao");
}
}
package laptop;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class BeanFactory {
public static Object getBean(String id) {
try {
// 建立SAXReader物件來讀取配置檔案
SAXReader reader = new SAXReader();
// 讀取配置檔案的內容,獲得Document物件
Document document = reader
.read(BeanFactory.class.getClassLoader().getResourceAsStream("factory.xml"));
// 利用XPath來讀取到class元素
Element beanElement = (Element) document.selectSingleNode("//bean[@id='" + id + "']");
// 獲取到class後的路徑
String value = beanElement.attributeValue("class");
System.out.println(value);
// 利用反射獲得實現類物件
Class clazz = Class.forName(value);
return clazz.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
factory.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="AcerDao" class="laptop.Acer"></bean>
<bean id="LenovoDao" class="laptop.Lenovo"></bean>
<bean id="DellDao" class="laptop.Dell"></bean>
</beans>
test類
package laptop;
public class Test {
public static void main(String[] args) {
// Laptop acer,lenovo,dell;
LaptopFactory af = new AcerFactory();
LaptopFactory lf = new LenovoFactory();
LaptopFactory df = new DellFactory();
af.getLaptopType().laptopType();
lf.getLaptopType().laptopType();
df.getLaptopType().laptopType();
}
}