前一个项目我们引用了开源软件Libvirt,Libvirt的实现非常不错,可以支持很多的Hypervisor。这两天再把设计模式翻出来看看,发现原来Libvirt是使用了Bridge设计模式,和Service Provider模式还有一定的区别,特用Java提供了框架如下:
Connect.java:这个类在Bridge模式中没有对应概念
package com.cisco.gendwang;
public class Connect
{
}
Driver.java:这个类在Bridge模式中相当于Implementator
package com.cisco.gendwang;
public interface Driver
{
Connect open(String url);
String getHostName(Connect conn);
void close(Connect conn);
}
EsxiDriver.java:这个类在Bridge模式中相当于ConcreteImplementator1
package com.cisco.gendwang;
public class EsxiDriver implements Driver
{
public EsxiDriver()
{
System.out.println("ESXi driver is loaded");
}
public Connect open(String url)
{
System.out.println("Get an ESXi connection");
return new Connect();
}
public String getHostName(Connect conn)
{
System.out.println("Host Name: CRDC-21");
return "CRDC-21";
}
public void close(Connect conn)
{
System.out.println("Close an ESXi connection");
}
}
package com.cisco.gendwang;
public class XenDriver implements Driver
{
public XenDriver()
{
System.out.println("XEN driver is loaded");
}
public Connect open(String url)
{
System.out.println("Get an XEN connection");
return new Connect();
}
public String getHostName(Connect conn)
{
System.out.println("Host Name: CRDC-90");
return "CRDC-90";
}
public void close(Connect conn)
{
System.out.println("Close an XEN connection");
}
}
Libvirt.java:这个类在Bridge中相当于Abstraction
package com.cisco.gendwang;
import java.util.HashMap;
import java.util.Map;
public class Libvirt
{
private Driver driver;
private static final Map<String, Driver> drivers = new HashMap<String, Driver>();
public static void registerDriver(String driverName, Driver driver)
{
drivers.put(driverName.toLowerCase(), driver);
}
public Connect virConnectOpen(String url)
{
int colonIndex = url.indexOf(":");
if(colonIndex == -1)
{
return null;
}
String prefix = url.substring(0, colonIndex);
driver = drivers.get(prefix.toLowerCase());
return driver.open(url);
}
public String virGetHostName(Connect conn)
{
return driver.getHostName(conn);
}
public void virConnectClose(Connect conn)
{
driver.close(conn);
}
}
Application.java: 这个类在Bridge中是Client
package com.cisco.gendwang;
public class Application
{
public static void main(String[] args)
{
Libvirt.registerDriver("ESXi", new EsxiDriver());
Libvirt.registerDriver("XEN", new XenDriver());
Libvirt libvirt1 = new Libvirt();
Connect conn1 = libvirt1.virConnectOpen("xen://10.74.125.90");
libvirt1.virGetHostName(conn1);
libvirt1.virConnectClose(conn1);
Libvirt libvirt2 = new Libvirt();
Connect conn2 = libvirt2.virConnectOpen("esxi://10.74.125.21");
libvirt2.virGetHostName(conn2);
libvirt2.virConnectClose(conn2);
}
}