很多网络设备都是支持共享的,如交换机、集线器等,多台终端计算机可以连接同一台网络设备,并通过该网络设备进行数据转发,如图所示,现用享元模式模拟共享网络设备的设计原理。
public class Switch implements NetworkDevice
{
private String type;
public Switch(String type)
{
this.type=type;
}
public String getType()
{
return this.type;
}
public void use()
{
System.out.println("Linked by switch, type is " + this.type);
}
}
public interface NetworkDevice
{
public String getType();
public void use();
}
public class Hub implements NetworkDevice
{
private String type;
public Hub(String type)
{
this.type=type;
}
public String getType()
{
return this.type;
}
public void use()
{
System.out.println("Linked by Hub, type is " + this.type);
}
}
import java.util.*;
public class DeviceFactory
{
private ArrayList devices = new ArrayList();
private int totalTerminal=0;
public DeviceFactory()
{
NetworkDevice nd1=new Switch("Cisco-WS-C2950-24");
devices.add(nd1);
NetworkDevice nd2=new Hub("TP-LINK-HF8M");
devices.add(nd2);
}
public NetworkDevice getNetworkDevice(String type)
{
if(type.equalsIgnoreCase("cisco"))
{
totalTerminal++;
return (NetworkDevice)devices.get(0);
}
else if(type.equalsIgnoreCase("tp"))
{
totalTerminal++;
return (NetworkDevice)devices.get(1);
}
else
{
return null;
}
}
public int getTotalDevice()
{
return devices.size();
}
public int getTotalTerminal()
{
return totalTerminal;
}
}
public class Client
{
public static void main(String args[])
{
NetworkDevice nd1,nd2,nd3,nd4,nd5;
DeviceFactory df=new DeviceFactory();
nd1=df.getNetworkDevice("cisco");
nd1.use();
nd2=df.getNetworkDevice("cisco");
nd2.use();
nd3=df.getNetworkDevice("cisco");
nd3.use();
nd4=df.getNetworkDevice("tp");
nd4.use();
nd5=df.getNetworkDevice("tp");
nd5.use();
System.out.println("Total Device:" + df.getTotalDevice());
System.out.println("Total Terminal:" + df.getTotalTerminal());
}
}
至此,你们可以多联系一下