Skip to content
Matt Tuttle edited this page Apr 3, 2015 · 1 revision

In its most basic form, a factory is used to create an instance of a protocol. It could also keep track of a list of all created protocols but for now let's look at the base type.

hxnet.base.Factory

The base Factory class takes a single argument protocol:Class<Protocol> in the constructor. This means you can pass a class implementing hxnet.interfaces.Protocol to the Factory and it will do the rest of the work. In fact the only other part of this class is the buildProtocol():Protocol function which creates an instance of the passed Protocol every time the function is called.

Take a look at an example of this class in use.

class Main
{
	static public function main()
	{
		var server = new hxnet.tcp.Server(new hxnet.base.Factory(hxnet.protocols.Telnet), 4000);
		server.start();
	}
}

You can see here that we pass a new instance of hxnet.base.Factory to hxnet.tcp.Server. This means that every time a client connects to the server the factory builds a new instance of the Telnet protocol. Pretty cool huh? But suppose we needed to keep track of the connected clients. In this case we need a custom factory.

class MyFactory extends hxnet.base.Factory
{
	public function new()
	{
		super();
		clients = new Array<Protocol>();
	}

	override public function buildProtocol():Protocol
	{
		var instance = super.buildProtocol();
		clients.push(instance);
		return instance;
	}

	static public function main()
	{
		var server = new hxnet.tcp.Server(new MyFactory(hxnet.protocols.Telnet), 4000);
		server.start();
	}

	private var clients:Array<Protocol>;
}
Clone this wiki locally