lundi 23 février 2015

Is there a name for this design pattern (dynamically wrapping around another class)?

Suppose I have a class uicontrolWrapper, which is a wrapper for a uicontrol (but does not subclass it). The uicontrol stuff is kept in a private property for uicontrolWrapper. Basically, I want to be able to do set/get against the wrapper, and calls would feed into uicontrol.


I could do this:



classdef uicontrolWrapper < handle
properties (Access = private)
uic
end
properties (Dependent)
Style
String
Value
...
end
methods
function set.Style(obj, val)
obj.uic.Style = val;
end
function val = get.Style(obj)
val = obj.uic.Style;
end
...
end


but hardcoding like this is obviously pretty ugly.


Or, I could do dynamically generate properties dependent on what I'm trying to wrap:



classdef uicontrolWrapper < dynamicprops
properties (Access = private)
uic
end
methods
function obj = uicontrolWrapper(hObj)
obj.uic = hObj;
cellfun(@(prop) obj.createProperty(prop, fields(get(hObj));
end
function createProperty(obj, prop)
p = addprop(obj, prop);
p.Dependent = true;
p.SetMethod = @setUicontrolProp;
p.GetMethod = @getUicontrolProp;

function setUicontrolProp(obj, val)
obj.uic.(prop) = value;
end
function val = getUicontrolProp(obj)
val = obj.uic.(prop);
end
end
end
end


The whole point is to avoid violating the Law of Demeter by not "reaching into" the property we're trying to adjust.


I don't know if this is a design pattern, but I've used this type of thing to wrap objects of different types when subclassing is for some reason or another inappropriate. (For instance, the matlab.ui.control.UIControl class is Sealed and cannot be subclassed.) Does this have an actual name and intended typical use?


Aucun commentaire:

Enregistrer un commentaire