桥接模式实例与解析
实例一:模拟毛笔
现需要提供大中小3种型号的画笔,能够绘制5种不同颜色,如果使用蜡笔,我们需要准备3*5=15支蜡笔,也就是说必须准备15个具体的蜡笔类。而如果使用毛笔的话,只需要3种型号的毛笔,外加5个颜料盒,用3+5=8个类就可以实现15支蜡笔的功能。本实例使用桥接模式来模拟毛笔的使用过程。
public class BigPen extends Pen
{
public void draw(String name)
{
String penType="大号毛笔绘制";
this.color.bepaint(penType,name);
}
}
public class Black implements Color
{
public void bepaint(String penType,String name)
{
System.out.println(penType + "黑色的"+ name + ".");
}
}
public class Blue implements Color
{
public void bepaint(String penType,String name)
{
System.out.println(penType + "蓝色的"+ name + ".");
}
}
public class Client
{
public static void main(String a[])
{
Color color;
Pen pen;
color=(Color)XMLUtilPen.getBean("color");
pen=(Pen)XMLUtilPen.getBean("pen");
pen.setColor(color);
pen.draw("鲜花");
}
}
public interface Color
{
void bepaint(String penType,String name);
}
public class Green implements Color
{
public void bepaint(String penType,String name)
{
System.out.println(penType + "绿色的"+ name + ".");
}
}
public class MiddlePen extends Pen
{
public void draw(String name)
{
String penType="中号毛笔绘制";
this.color.bepaint(penType,name);
}
}
public abstract class Pen
{
protected Color color;
public void setColor(Color color)
{
this.color=color;
}
public abstract void draw(String name);
}
public class Red implements Color
{
public void bepaint(String penType,String name)
{
System.out.println(penType + "红色的"+ name + ".");
}
}
public class SmallPen extends Pen
{
public void draw(String name)
{
String penType="小号毛笔绘制";
this.color.bepaint(penType,name);
}
}
public class White implements Color
{
public void bepaint(String penType,String name)
{
System.out.println(penType + "白色的"+ name + ".");
}
}
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtilPen
{
//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象
public static Object getBean(String args)
{
try
{
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("configPen.xml"));
NodeList nl=null;
Node classNode=null;
String cName=null;
nl = doc.getElementsByTagName("className");
if(args.equals("color"))
{
//获取包含类名的文本节点
classNode=nl.item(0).getFirstChild();
}
else if(args.equals("pen"))
{
//获取包含类名的文本节点
classNode=nl.item(1).getFirstChild();
}
cName=classNode.getNodeValue();
//通过类名生成实例对象并将其返回
Class c=Class.forName(cName);
Object obj=c.newInstance();
return obj;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
配置文件configPen.xml
<?xml version="1.0"?>
<config>
<className>Blue</className>
<className>SmallPen</className>
</config>