題目
1、有一個OEM制造商代理做HP筆記本(Laptop),後來該制造商得到了更多的品牌筆記本電腦的訂單Acer,Lenovo,Dell,該OEM商發現,如果一次同時做很多個牌子的本本,有些不利于管理。利用工廠模式改善設計,用java控制台應用程式實作該OEM制造商的工廠模式。
1.定義電腦品牌類型接口類型
//電腦品牌類型
public interface Laptop {
public void laptopType();
}
//Acer
public class Acer implements Laptop {
@Override
public void laptopType() {
System.out.println("Acer");
}
}
//Dell
public class Dell implements Laptop{
@Override
public void laptopType() {
System.out.println("Dell");
}
}
//Lenovo
public class Lenovo implements Laptop{
@Override
public void laptopType() {
System.out.println("Lenovo");
}
}
電腦品牌類型工廠實體類
//電腦品牌類型工廠實體類
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");
}
}
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();
}
}
運作結果
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL4ITNzMTMyMTMyETMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)