- 
                Notifications
    You must be signed in to change notification settings 
- Fork 9
Factories
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.
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>;
}