概要
Factory Method パターンは、インスタンス生成に Template Method の考え方を応用した、デザインパターンの一つである。
ソースコード
+framework/Product.m
classdef (Abstract) Product
methods (Abstract)
use(obj)
end
end
+framework/Factory.m
classdef (Abstract) Factory
methods (Access = public, Sealed)
function product = create(obj, owner)
arguments (Input)
obj framework.Factory
owner char {mustBeTextScalar}
end
arguments (Output)
product (1,1) framework.Product
end
product = obj.createProduct(owner);
obj.registerProduct(product);
end
end
methods (Abstract, Access = protected)
product = createProduct(obj, owner)
registerProduct(obj, product)
end
end
+idcard/IDCard.m
classdef IDCard < framework.Product
properties (Access = private)
owner char {mustBeTextScalar}
end
methods (Access = public)
function obj = IDCard(owner)
arguments (Input)
owner char {mustBeTextScalar}
end
arguments (Output)
obj (1,1) idcard.IDCard
end
disp([owner, 'のカードを作ります。']);
obj.owner = owner;
end
function use(obj)
disp([obj.owner, 'のカードを使います。']);
end
function owner = getOwner(obj)
owner = obj.owner;
end
end
end
+idcard/IDCardFactory.m
classdef IDCardFactory < framework.Factory
properties (Access = private)
owners char {mustBeMatrix}
end
methods (Access = protected)
function product = createProduct(obj, owner)
arguments (Input)
obj idcard.IDCardFactory
owner char {mustBeTextScalar}
end
arguments (Output)
product framework.Product
end
product = idcard.IDCard(owner);
end
function registerProduct(obj, product)
arguments (Input)
obj idcard.IDCardFactory
product framework.Product
end
obj.owners(end + 1, :) = product.getOwner();
end
end
methods (Access = public)
function owners = getOwners(obj)
arguments (Input)
obj idcard.IDCardFactory
end
arguments (Output)
owners char
end
owners = obj.owners;
end
end
end
main.m
function main
factory = idcard.IDCardFactory();
card1 = factory.create('結城浩');
card2 = factory.create('とむら');
card3 = factory.create('佐藤花子');
card1.use();
card2.use();
card3.use();
end
実行結果
>> main
結城浩のカードを作ります。
とむらのカードを作ります。
佐藤花子のカードを作ります。
結城浩のカードを使います。
とむらのカードを使います。
佐藤花子のカードを使います。