实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
类图 ![](https://i-blog.csdnimg.cn/blog_migrate/d6ec0c3ef553c769c9f270fe6bedae4e.png)
源代码
/**
* 抽象汽车类
*/
public abstract class Vehicle
{
protected Road road;
//为汽车设置行驶的马路
public void setRoad(Road road)
{
this.road = road;
}
//抽象行驶方法
public abstract void drive();
}
public class Bus extends Vehicle
{
//bus的行驶方法
@Override
public void drive()
{
String carType = "bus";
this.road.bedrive(carType);
}
}
public class Car extends Vehicle
{
//car的行驶方法
@Override
public void drive()
{
String carType = "car";
this.road.bedrive(carType);
}
}
public interface Road
{
void bedrive(String carType);
}
public class ConcreteRoad implements Road
{
//水泥路
@Override
public void bedrive(String carType)
{
System.out.println(carType+"在水泥路行驶");
}
}
public class PitchRoad implements Road
{
//沥青路
@Override
public void bedrive(String carType)
{
System.out.println(carType + "在沥青路行驶");
}
}
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XMLUtil
{
public static Object getBean(String args)
{
try
{
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("src/main/resources/config9.xml"));
Node classNode = null;
NodeList nl = doc.getElementsByTagName("className");
if (args.equals("road"))
{
classNode = nl.item(0).getFirstChild();
} else if (args.equals("vehicle"))
{
classNode = nl.item(1).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)
{
//从xml配置文件动态获取汽车类型
Vehicle vehicle = (Vehicle) XMLUtil.getBean("vehicle");
//动态获取路的类型
Road road = (Road) XMLUtil.getBean("road");
//给汽车设置行驶的路
vehicle.setRoad(road);
//调用汽车的行驶方法
vehicle.drive();
}
}
config9.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<className>Tutorial_9.ConcreteRoad</className>
<className>Tutorial_9.Bus</className>
</config>