享元模式实例与解析实例二:共享网络设备(有外部状态)

该示例展示了如何在Java中实现网络设备(Switch和Hub)的共享,每个设备分配不同的端口供多台计算机使用。通过DeviceFactory类管理不同类型的网络设备,并跟踪已连接的终端数量。客户端代码演示了获取设备并设置端口的过程。
摘要由CSDN通过智能技术生成

实例二:共享网络设备(有外部状态) 虽然网络设备可以共享,但是分配给每一个终端计算机的端口(Port)是不同的,因此多台计算机虽然可以共享同一个网络设备,但必须使用不同的端口。我们可以将端口从网络设备中抽取出来作为外部状态,需要时再进行设置。

 

 

 

 

public class Switch implements NetworkDevice
{
	private String type;
	
	public Switch(String type)
	{
		this.type=type;
	}
	
	public String getType()
	{
		return this.type;
	} 
	
	public void use(Port port)
	{
		System.out.println("Linked by switch, type is " + this.type + ", port is " + port.getPort());
	}
}

 

 

public class Port
{
	private String port;
	
	public Port(String port)
	{
		this.port=port;	
	}
	
	public void setPort(String port)
	{
		this.port=port;
	}
	
	public String getPort()
	{
		return this.port;
	}
}

 

 

public interface NetworkDevice
{
	public String getType();
	public void use(Port port);
}
public class Hub implements NetworkDevice
{
	private String type;
	
	public Hub(String type)
	{
		this.type=type;
	}
	
	public String getType()
	{
		return this.type;
	} 
	
	public void use(Port port)
	{
		System.out.println("Linked by Hub, type is " + this.type + ", port is " + port.getPort());
	}	
}

 

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(new Port("1000"));
		
		nd2=df.getNetworkDevice("cisco");
		nd2.use(new Port("1001"));
		
		nd3=df.getNetworkDevice("cisco");
		nd3.use(new Port("1002"));
		
		nd4=df.getNetworkDevice("tp");
		nd4.use(new Port("1003"));
		
		nd5=df.getNetworkDevice("tp");
		nd5.use(new Port("1004"));
		
		System.out.println("Total Device:" + df.getTotalDevice());
		System.out.println("Total Terminal:" + df.getTotalTerminal());
	}
}

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值