现需要设计一个可以模拟各种动物行为的机器人,在机器人中定义了一系列方法,如机器人叫喊方法cry()、机器人移动方法move()等。如果希望在不修改已有代码的基础上使得机器人能够像狗dog一样叫wang(),像狗一样跑run(),使用 1 模式进行系统设计。 import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import java.io.*; public class XMLUtil { // 该方法用于从 XML 配置文件中提取具体类类名,并返回一个实例对象 public static Object getBean() { try { // 创建文档对象 DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dFactory.newDocumentBuilder(); Document doc; doc = builder.parse(new File("config.xml")); // 获取包含类名的文本节点 NodeList nl = doc.getElementsByTagName("className"); Node classNode=nl.item(0).getFirstChild(); String cName=classNode.getNodeValue(); // 通过类名生成实例对象并将其返回 Class c=Class.forName(cName); Object obj=c.newInstance(); return obj; } catch(Exception e) { e.printStackTrace(); return null; } } } public class Client { public static void main(String args[]) { Robot robot=(Robot)XMLUtil. 2 ; robot.cry(); robot.move(); } } public class Bird { public void tweedle() { System.out.println(" 鸟儿叽叽叫! "); } public void fly() { System.out.println(" 鸟儿快快飞! "); } } public interface Robot { public void cry(); public void move(); } public class BirdAdapter extends Bird implements 3 { public void cry() { System.out.print(" 机器人模仿: "); super.tweedle(); } public void move() { System.out.print(" 机器人模仿: "); super.fly(); } } public class Dog { public void wang() { System.out.println(" 狗汪汪叫! "); } public void run() { System.out.println(" 狗快快跑! "); } } public class DogAdapter extends Dog implements Robot { public void cry() { System.out.print(" 机器人模仿: "); super. 4 ; } public void 5 { System.out.print(" 机器人模仿: "); super.run(); } }