VBA と Java のオブジェクト指向プログラミング

Top > Excel VBA でデザインパターン > Singletonパターン

Singletonパターン


SingletonパターンのサンプルプログラムをExcelVBAで記述すると以下のように
なります。モジュールごとにプログラムを示します。

標準モジュール:modCSingleton
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
クラスモジュール:clsCSingleton
Option Explicit

<font color="green">'コンストラクタ</font>
Public Sub init1()
    Debug.Print "インスタンスを生成しました。"
End Sub

標準モジュール:modCMain
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.

0
Posted by awesome things! 2014年01月22日(水) 05:22:35 返信

gihxdh Fantastic post.Much thanks again.

0
Posted by tips about seo 2013年12月20日(金) 08:18:48 返信

VBADP05 - VBA 鐃緒申 Java 鐃塾ワ申鐃瞬ワ申鐃緒申鐃緒申鐃夙指醐申鐃竣ワ申鐃緒申鐃淳ワ申 - Seesaa Wiki鐃淑ワ申鐃緒申鐃緒申鐃緒申 for 鐃緒申鐃殉¥申鐃夙フワ申鐃緒申 ≪潟若 順 http://www.pslcbi.com/moncler2014.html

0
Posted by ≪潟若 順 2013年12月10日(火) 05:06:38 返信

VBADP05 - VBA 鐃緒申 Java 鐃塾ワ申鐃瞬ワ申鐃緒申鐃緒申鐃夙指醐申鐃竣ワ申鐃緒申鐃淳ワ申 - Seesaa Wiki鐃淑ワ申鐃緒申鐃緒申鐃緒申 for 鐃緒申鐃殉¥申鐃夙フワ申鐃緒申 ≪潟若 筝荀 http://www.pslcbi.com/moncler2014.html

0
Posted by ≪潟若 筝荀 2013年12月08日(日) 01:42:29 返信

SKngO0 <a href="http://uufsrmiwhgdf.com/">uufsrmiwhgdf</a>, [url=http://qfxsruvkiznz.com/]qfxsruvkiznz[/url], [link=http://juffipnwlpar.com/]juffipnwlpar[/link], http://ksaxphtkxibx.com/

0
Posted by fqfxphenf 2013年11月14日(木) 23:52:08 返信

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

編集にはIDが必要です