Last active
October 29, 2021 06:25
-
-
Save hoppfrosch/ab81f576ad654ae2b57f39201fc6e439 to your computer and use it in GitHub Desktop.
Recipe for Singleton class wit AutoHotkey
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;~ This is a singleton class - taken from: http://www.programering.com/a/MDN4YDMwATU.html | |
class Singleton | |
{ | |
;~ Single cases registered property | |
static _myInstance := 0 | |
;~ Instantiation counts | |
static _instanceCount := 0 | |
;~ test property | |
_myVar := 0 | |
__New() { | |
MsgBox % "step2: <new> to create a new instance" | |
if IsObject( this._myInstance ) { | |
MsgBox % "Singleton class is already instantiated, use the <getInstance> method to obtain the existing singleton instance" | |
return this._myInstance | |
} | |
} | |
getInstance() { | |
MsgBox % "step1: <getInstance> to get the singleton" | |
if ( IsObject( this._myInstance ) = 0 ) { | |
this._instanceCount++ | |
this._myInstance := new Singleton() | |
} | |
return this._myInstance | |
} | |
; accessor to test property | |
myVar[] { | |
get { | |
this._myVar := this._myvar + 1 | |
return this._myvar | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Include %A_ScriptDir% | |
#Include Singleton.ahk | |
MsgBox % "**** The first run should use the New function." | |
testFunc() | |
MsgBox % "**** The second run should not use the New function." | |
testFunc() | |
MsgBox % "**** The third run should not use the New function." | |
testFunc() | |
ExitApp | |
testFunc() | |
{ | |
objA := Singleton.getInstance() | |
MsgBox % "myVar: " ObjA.myVar "`ninstantiation times: " objA._instanceCount | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment