一、 实验目的与要求
1.练习使用工厂模式。设计相关的模拟场景并进行实施,验证模式特性,掌握其优缺点。
2.实验结束后,对相关内容进行总结。
二、实验内容
1.模式应用场景说明
Decis创建一个获取多套餐信息,包含A套餐(鸡肉堡+橙汁)B套餐(炸鸡和咖啡)构造一份完整套餐,返回给顾客。
2.应用场景
3.实现代码与解释
3.1产品类Meal
package 创建者模式;public class Meal {private String food;private String drink;public void setFood(String food) {this.food=food;}public void setDrink(String drink) {this.drink=drink;}public String getFood() {return(this.food);}public String getDrink() {return(this.drink);}
}
3.2抽象构造类MealBuilder
package 创建者模式;public abstract class MealBuilder {protected Meal meal=new Meal();public abstract void buildFood();public abstract void buildDrink();public Meal getMeal() {return meal;}
}
3.3具体构造类SubMealBuilderA
package 创建者模式;public class SubMealBuilderA extends MealBuilder{public void buildFood() {meal.setFood("一个鸡肉堡");}public void buildDrink() {meal.setDrink("一杯橙汁");}
}
3.4具体构造类SubMealBuilderB
package 创建者模式;public class SubMealBuilderB extends MealBuilder{public void buildFood() {meal.setFood("一只炸鸡");}public void buildDrink() {meal.setDrink("一杯咖啡");}
}
3.5指挥者类DecisWaiter
package 创建者模式;public class DecisWaiter {private MealBuilder mb;public void setMealBuilder(MealBuilder mb) {this.mb=mb;}public Meal construct() {mb.buildFood();mb.buildDrink();return mb.getMeal();}
}
3.6客户端测试类Client
package 创建者模式;public class Client {public static void main(String args[]) {MealBuilder mb=(MealBuilder)XMLUtil.getBean();DecisWaiter waiter=new DecisWaiter();waiter.setMealBuilder(mb);Meal meal=waiter.construct();System.out.println("套餐组成:");System.out.println(meal.getFood());System.out.println(meal.getDrink());}
}
3.7辅助代码:获取外界配置文件的信息
package 创建者模式;
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("C:\\Users\\33132\\eclipse-workspace\\创建者模式\\src\\创建者模式\\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;}}
}
3.8外界配置文件
4.结果及分析
4.1将配置文件节点改成SubMealBuilderA
4.2将配置文件节点改成SubMealBuilderB
三、实验总结
优点:指挥者类针对抽象建造者类编程,系统扩展方便,符合“开闭原则”;
缺点:产品内部变化复杂,则会使系统变得庞大。