---
title: "Autohotkey_L的单例类实现"
author: "fonny"
date: "2013-12-08T20:57:30Z"
tags: []
categories: ["编程语言"]
slug: "autohotkey-l"
draft: false
lastmod: "2013-12-08T20:57:30Z"
id: 1986852
url: "https://fonny.iteye.com/blog/1986852"
---

# 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)  
}