0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MATLAB言語で学ぶ「Java言語で学ぶデザインパターン入門」ノート #5 Singleton

Posted at

概要

Singleton パターンは、インスタンスが1つだけしか存在しないことを保証する、デザインパターンの一つである。

ソースコード

Singleton.m
classdef Singleton < handle
    properties (Access = private, Constant)
        singleton = Singleton()
    end
    methods (Access = private)
        function obj = Singleton()
            arguments (Output)
                obj Singleton
            end
            disp('インスタンスを生成しました。');
        end
    end
    methods (Access = public, Static)
        function obj = getInstance()
            obj = Singleton.singleton;
        end
    end
end
main.m
function main
disp('Start.');
obj1 = Singleton.getInstance();
obj2 = Singleton.getInstance();
if isequal(obj1, obj2)
    disp('obj1とobj2は同じインスタンスです。');
else
    disp('obj1とobj2は同じインスタンスではありません。');
end
disp('End.');
end

実行結果

>> main
Start.
インスタンスを生成しました。
obj1とobj2は同じインスタンスです。
End.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?