CREATE STATIC
CREATE STATIC
这些关键字被单独放置在类文件的起始位置时,将告知解释器“当将非静态标志作为类的名称时,在执行中将创建一个类的自动隐藏的实例”。
如果使用这个特性,类构造程序(特殊的方法
_new
将被无参数调用。
该特性已经被用于
Form和
Settings类的内部。
以下是
Settings 类代码的摘录:
Example: Settings.class (gb.settings)
Export
Create Static
' ...
Public Sub _new(Optional Path As String, Optional Title As String)
' ...
If Not Path Then
Path = Settings.DefaultDir &/ Application.Name & ".conf"
Explanation
Consider this line of Gambas code:
Print Settings["Key"]
It looks like the array accessor method
_get() is applied to the Settings
class to get the value corresponding to the key "Key", but this doesn't make sense as the _get() method of Settings is not
static but dynamic, i.e. it does not belong to the class but to some object of the class. But since Settings is CREATE STATIC, the interpreter will create the automatic instance of the Settings class behind the scenes and use this object for the array access.
The automatic instance of Settings is, as explained above, constructed without arguments. In the Settings.class code snippet above you see that in this case
Path is set to the default configuration file path
Settings.DefaultDir &/ Application.Name & ".conf"
.
In conclusion, whenever you use the class name "Settings" like an object (by using dynamic symbols on it), you actually use the hidden automatic instance of the Settings class, which is linked to the default configuration file.
Singletons
This feature, together with
CREATE PRIVATE, can be used to implement the object-oriented programming
singleton pattern. CREATE STATIC allows you to use a class name like an object while CREATE PRIVATE makes the class uninstantiable (except for the automatic instance).
Instead of a CREATE STATIC + CREATE PRIVATE class you can also effectively use a
module in Gambas!
参见