Top > Excel VBA でデザインパターン > Singletonパターン
Top > Excel VBA でデザインパターン > Singletonパターン
Option Explicit
<font color="green">'VBA のクラスにはクラスフィールドを定義できないので</font>
<font color="green">'標準モジュールに定義された変数を変わりに使う</font>
Private mobjSingletion As clsCSingleton
<font color="green">'VBA のクラスにはコンストラクタを定義できないので</font>
<font color="green">'標準モジュールに定義されたプロシージャを変わりに使う</font>
Private Function init1() As clsCSingleton
Dim obj As clsCSingleton
Set obj = New clsCSingleton
obj.init1
Set init1 = obj
End Function
<font color="green">'VBA のクラスにはクラスメソッドを定義できないので</font>
<font color="green">'標準モジュールに定義されたプロシージャを変わりに使う</font>
Public Function getInstance() As clsCSingleton
<font color="green"> 'VBAではインスタンスが設定されていないことは Is Nothing で判断する。</font>
If (mobjSingletion Is Nothing) Then
<font color="green"> 'VBA で Private xxx As New yyy と定義しても、</font>
<font color="green"> '実際にプロパティやメソッドを呼び出さないと</font>
<font color="green"> 'yyy のインスタンスが生成されないので</font>
<font color="green"> 'getInstance メソッドの中でインスタンスを生成している</font>
Set mobjSingletion = modCSingleton.init1
End If
Set getInstance = mobjSingletion
End Function
Option Explicit
<font color="green">'コンストラクタ</font>
Public Sub init1()
Debug.Print "インスタンスを生成しました。"
End Sub
Option Explicit
<font color="green">'メイン処理1</font>
Sub main1()
Dim obj1 As clsCSingleton
Dim obj2 As clsCSingleton
Debug.Print "Start."
Set obj1 = modCSingleton.getInstance
Set obj2 = modCSingleton.getInstance
<font color="green"> 'VBA ではインスタンスの比較は Is で行う</font>
<font color="green"> 'Javaの equals のように値が等しいかどうかまでは判断されない</font>
If (obj1 Is obj2) Then
Debug.Print "obj1とobj2は同じインスタンスです。"
Else
Debug.Print "obj1とobj2は同じインスタンスではありません。"
End If
Debug.Print "End."
End Sub
Top > Excel VBA でデザインパターン > Singletonパターン
このページへのコメント
Mf8aLc Really enjoyed this blog.Much thanks again.
gihxdh Fantastic post.Much thanks again.
VBADP05 - VBA 鐃緒申 Java 鐃塾ワ申鐃瞬ワ申鐃緒申鐃緒申鐃夙指醐申鐃竣ワ申鐃緒申鐃淳ワ申 - Seesaa Wiki鐃淑ワ申鐃緒申鐃緒申鐃緒申 for 鐃緒申鐃殉¥申鐃夙フワ申鐃緒申 ≪潟若 順 http://www.pslcbi.com/moncler2014.html
VBADP05 - VBA 鐃緒申 Java 鐃塾ワ申鐃瞬ワ申鐃緒申鐃緒申鐃夙指醐申鐃竣ワ申鐃緒申鐃淳ワ申 - Seesaa Wiki鐃淑ワ申鐃緒申鐃緒申鐃緒申 for 鐃緒申鐃殉¥申鐃夙フワ申鐃緒申 ≪潟若 筝荀 http://www.pslcbi.com/moncler2014.html
SKngO0 <a href="http://uufsrmiwhgdf.com/">uufsrmiwhgdf</a>, [url=http://qfxsruvkiznz.com/]qfxsruvkiznz[/url], [link=http://juffipnwlpar.com/]juffipnwlpar[/link], http://ksaxphtkxibx.com/