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?
This is the Decorator Pattern -- creating a tool that decorates new functionality onto existing objects (at possibly many different times) specifically without affecting any other instances of the same type (or affecting them in an explicit way if desired).
This differs from Proxy pattern in the sense that you're not defering the task of dispatching the right operation to the proxy, you're actually grafting new functionality onto the object.
I believe you're asking about the Proxy design pattern here (provide an interface to other objects by creating a wrapper class as the proxy).
A couple of its benefits are adding security access and simplifying the API to the wrapped object (the proxy can provide a simple API so that the client code does not have to deal with the complexity of the object of interest).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With