I need to augment the behavior of a class using external methods, hence I leverage the strategy pattern.
First I define an interface for the signature of methods:
class ILabel(ABC):
@abstractmethod
def get_label(self, obj):
pass
and an implementation of that interface:
class Label(ILabel):
def __init__(self, prefix):
self.prefix = prefix
def get_label(self, obj):
return self.prefix + str(obj)
And the class that I would like to augment its algorithm:
class Merchandise:
def get_label(self, obj):
return str(obj)
def display(self, obj, get_label=None):
if get_label:
self.get_label = types.MethodType(get_label, self)
print(self.get_label(obj))
And finally the caller:
# default behavior
x = Merchandise().display("an_obj")
# augmented behavior
label = Label("a_prefix_")
y = Merchandise().display("an_obj", label)
print(f"Default output: {x}")
print(f"Augmented output: {y}")
the output should be:
Default output: an_obj
Augmented output: a_prefix_an_obj
Two questions:
-
Given instead of an "orphan" method (for the lack of a better word), I am sending a method within a class with reference to self; is this still considered strategy pattern, or a different pattern is closer to this design?
-
Since I pass a reference to the
Merchandise
when registering the method (i.e.,types.MethodType(get_label, self)
), the correct definition ofget_label
in theLabel
class is:def get_label(self, merchandise_self, obj):
The question is, is there any better naming convention for
merchandise_self
?
Aucun commentaire:
Enregistrer un commentaire