Make subclasses act like methods

Put simple Tips and Tricks that are not entire Tutorials in this forum
User avatar
runie
Posts: 304
Joined: 03 May 2014, 14:50
Contact:

Make subclasses act like methods

11 Oct 2017, 01:23

One of the usecases for this is if you want to have a method but the method ends up being large and messy, so you would rather split up the method code but still be able to call it as a method.

Code: Select all

MyClass.SubClass("Test", "Second", 3)

Class MyClass {
	Class SubClass extends MyClass.Functor {
		Call(Params*) {
			msgbox % this.ParseObject(Params)
		}
		
		ParseObject(Params) {
			for Index, Param in Params
				ParamText .= "`n" Param
			return SubStr(ParamText, 2)
		}
	}
	
	Class Functor {
		__Call(NewEnum, Param*) {
			(new this).Call(Param*)
		}
	}
}
Here, MyClass.SubClass(Params) would create a new instance of MyClass.SubClass and call the .Call() method in that instance. When execution is done, the last reference to the instance is released.

This implies that a new instance of MyClass.SubClass is created for each 'method' call, so inside the SubClass you can do whatever you want with the instance without worrying about messing it up for later calls.

The code can be thought of as a more complicated version of this:

Code: Select all

MyClass.SubClass("Test", "Second", 3)

Class MyClass {
	SubClass(Param*) {
		for Index, Param in Params
			ParamText .= "`n" Param
		msgbox % SubStr(ParamText, 2)
	}
}
Also I learnt about this design pattern from COCO's JSON encoder/decoder: https://github.com/cocobelgica/AutoHotk ... r/JSON.ahk

Return to “Tips and Tricks (v1)”

Who is online

Users browsing this forum: No registered users and 13 guests