24.3 完整解决方案
[java] view plaincopy
-
//电影票类:环境类
-
class
MovieTicket { -
private double price; -
private Discount //维持一个对抽象折扣类的引用discount; -
-
public void setPrice( doubleprice) { -
this.price = price; -
} -
-
//注入一个折扣类对象 -
public void setDiscount(Discount discount) { -
this.discount = discount; -
} -
-
public double getPrice() { -
//调用折扣类的折扣价计算方法 -
return discount.calculate( this.price); -
} - }
-
-
//折扣类:抽象策略类
-
interface
Discount { -
public double calculate( doubleprice); - }
-
-
//学生票折扣类:具体策略类
-
class
StudentDiscount implementsDiscount { -
public double calculate( doubleprice) { -
System.out.println("学生票:"); -
return price 0.8;* -
} -
}
-
-
//儿童票折扣类:具体策略类
-
class
ChildrenDiscount implementsDiscount { -
public double calculate( doubleprice) { -
System.out.println("儿童票:"); -
return price 10;- -
} -
}
-
-
//VIP会员票折扣类:具体策略类
-
class
VIPDiscount implementsDiscount { -
public double calculate( doubleprice) { -
System.out.println("VIP票:"); -
System.out.println("增加积分!"); -
return price 0.5;* -
} - }
[java] view plaincopy
-
import
javax.xml.parsers.*; -
import
org.w3c.dom.*; -
import
org.xml.sax.SAXException; -
import
java.io.*; -
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_r("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; -
} -
} - }
[html] view plaincopy