我正在创建一个工具箱,我想要动态地将特定属性添加到类的实例中,同时限制用户添加属性的能力。
我正在考虑一种称为模型的对象类的基线功能。每个模型都可以用额外的功能来装饰,比如Bootstrap CI、置换测试等。
我希望将额外的功能附加到对象实例中。据我所知,使用装饰器模式将在其中存储我的模型的实例,但如果有多个装饰器作用于同一个对象,我就不确定该怎么做-例如,启动CI和置换测试。我认为只有通过调用为模型类定义的方法才能动态地向对象添加属性,这将是最好的选择,但我不知道如何编程,同时使用户无法向对象添加属性。
发布于 2015-09-09 23:16:16
我会使用依赖属性和重载方法来进行设计,而不是使用动态属性。例如:
模型.m
classdef (Abstract) Model < handle
properties (Access = public)
commonProp1
commonProp2 % etc
end
properties (Dependent, GetAccess = public, SetAccess = private)
ciEstimate
end
properties (Access = private)
isFitted = false;
ciEstimateInternal = []
end
methods (Abstract, Access = public)
ciEstimate = calcCIEstimate(obj)
fit(obj)
end
methods
function val = get.ciEstimate(obj)
if ~obj.isFitted
error('Model not yet fitted.')
end
if isempty(obj.ciEstimateInternal)
obj.ciEstimateInternal = obj.calcCIEstimate;
end
val = obj.ciEstimateInternal;
end
end
endType1Model.m
classdef Type1Model < Model
methods (Access = public)
function fit(obj)
% Do some fitting stuff for a type 1 model
obj.isFitted = true;
end
function ciEstimate = calcCIEstimate(obj)
% Do it in a bootstrap way
end
end
endType2Model.m
classdef Type2Model < Model
methods (Access = public)
function fit(obj)
% Do some fitting stuff for a type 2 model
obj.isFitted = true;
end
function ciEstimate = calcCIEstimate(obj)
% Do it in a posterior variance way
end
end
end使用这种设计,每种模型类型都可以用自己的方式进行拟合,并可以用自己的方式计算CI估计。模型将具有一致的属性ciEstimate,该属性在第一次访问时按需计算,否则将在内部存储在模型对象中(在ciEstimateInternal中)。
https://stackoverflow.com/questions/32478852
复制相似问题