public interface Tool {
void draw();
void erace();
}
class RoundTool implements Tool {
@Override
public void draw() {
System.out.println("绘制一个圆形");
}
@Override
public void erace() {
System.out.println("擦除一个圆形");
}
}
class SquareTool implements Tool {
@Override
public void draw() {
System.out.println("绘制一个方形");
}
@Override
public void erace() {
System.out.println("擦除一个方形");
}
}
class TriangeTool implements Tool {
@Override
public void draw() {
System.out.println("绘制一个三角形");
}
@Override
public void erace() {
System.out.println("擦除一个三角形");
}
}
public class DrawToolFactory {
public static Tool getDrawTool(String type){
Tool tool=null;
if(type.equalsIgnoreCase("round")){
tool=new RoundTool();
System.out.println("初始化圆形工具!");
}else if(type.equalsIgnoreCase("square")){
tool=new SquareTool();
System.out.println("初始化方形工具!");
}else if(type.equalsIgnoreCase("triange")){
tool=new TriangeTool();
System.out.println("初始化三角形工具!");
}else{
throw new UnsupportedClassVersionError("不支持的类型");
}
return tool;
}
}
/**
* 解析器
*/
public class XMLUtil {
public static String getDrawTool() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc;
doc=builder.parse(new File("config.xml"));
NodeList nl=doc.getElementsByTagName("drawType");
Node classNode=nl.item(0).getFirstChild();
String drawType=classNode.getNodeValue().trim();
return drawType;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
/**
* xml
*/
<?xml version="1.0"?>
<config>
<drawType>triange</drawType>
</config>
/**
* 运行类
*/
public static void main(String[]args){
Tool round= DrawToolFactory.getDrawTool("round");
round.draw();
round.erace();
Tool square= DrawToolFactory.getDrawTool("square");
square.draw();
square.erace();
Tool triange=DrawToolFactory.getDrawTool(XMLUtil.getDrawTool());
triange.draw();
Tool tool=DrawToolFactory.getDrawTool("error");
}