ITeye博客

Autohotkey_L的单例类实现

fonny · 2013-12-08 20:57 · Autohotkey · 编程语言 · Markdown

Autohotkey_L的单例类实现

今天尝试了一下单例模式的AHK写法,貌似成功了.

如果成功了,意味着可以使用MVC like的框架形式构筑大型程序.

具体代码如下:

 

%A_ScriptDir%\gIncludes\Cls_MyBase.ahk

 

;~ 这是一个单例类
class Cls_MyBase
{
    
    ;~ 单例注册属性
    static _myInstance := 0
    
    ;~ 实例化次数计数
    static _instanceCount := 0
    
    ;~ 测试属性
    _myVar := 0
    
    ;~ 新的实例化,参数必须为此单例的全局变量
    __New()
    {
        trace("step1`: new元函数实例化",2)
        if IsObject( this._myInstance )
        {
            trace("已经实例化的单例类`,请使用getInstance方法获取Cls_MyBase实例",2)
            return this._myInstance
        }
    }
    
    getInstance()
    {
        trace("step2`: getInstance方法获取实例",2)
        ;~ 单例注册属性
        ;~ static _myInstance
        
        if ( IsObject( this._myInstance ) = 0 )
        {
            this._instanceCount**++**
            this._myInstance := new Cls_MyBase()
        }
        
        return this._myInstance
    }
    
    getMyVar()
    {
        trace("step3`: 内置方法获取属性",2)
        this._myVar**+
+**
        return this._myVar
    }
}

 

testSingleton.ahk

 

;~ 测试单例模式
;~ Test Singleton mode
;~ Author: Fonny [ fjxhkj@gmail.com ]
;~ AutoHotkey Version 1.1.13.1
;~ http://www.autohotkey.com/

**#**Warn
**#**NoEnv
;~ #Persistent
**#**SingleInstance force
**#**HotkeyInterval 1000 ;默认2000毫秒,重复热键的间隔时间
**#**MaxHotkeysPerInterval 100 ;在#HotkeyInterval允许的情况下,最多可以触发的热键数量
**#**Include, %A_ScriptDir%
**#**WinActivateForce

SetWorkingDir %A_ScriptDir%
Process, Priority, , High
;~ SetBatchLines, -1
SetDefaultMouseSpeed, 0
;~ SetMouseDelay, 0 ;鼠标点击后的延迟,影响后续的输入稳定性.系统默认10-15
;~ SetKeyDelay, 0
;~ 匹配开头字符
;~ SetTitleMatchMode, 1
;~ 匹配任意位置
SetTitleMatchMode, 2
;~ 坐标系统使用包含windows样式边框的
CoordMode, Window
;~ SendMode Input

;~ ======================================S=T=A=R=T====
;~ Includes
;~ ==================================================================

**#**Include %A_ScriptDir%

**#**Include gIncludes\Cls_MyBase.ahk

;~ ======================================
;~ End Includes
;~ ======================================E=N=D=======================

#x::
Reload
return

#c::
testFunc()
trace("第二次运行`n将不会使用New元函数实例化了", 2)
testFunc()
return

testFunc()
{
    objA := Cls_MyBase.getInstance()
        
    trace("内置属性objA`.var is `: " . objA.getMyVar() . "`n实例化次数 `:" . objA._instanceCount, 2)
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。