Skip to content

Instantly share code, notes, and snippets.

@hoppfrosch
Last active October 29, 2021 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoppfrosch/ab81f576ad654ae2b57f39201fc6e439 to your computer and use it in GitHub Desktop.
Save hoppfrosch/ab81f576ad654ae2b57f39201fc6e439 to your computer and use it in GitHub Desktop.
Recipe for Singleton class wit AutoHotkey
;~ 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
}
}
}
#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