mardi 28 novembre 2017

Does this transformation pattern have a name?

A random thought just came to mind: it is possible to implement accessors and mutators by passing a function that takes, transforms, and returns data. Of course, far more than accessors and mutators can be implemented with such a capability, but transformations can be very simple in their design.

  1. Does this design pattern have a name?
  2. Are there any languages that regularly use this pattern?

As an example, the Child class uses simple transformations to create an accessor and mutator:

#! /usr/bin/env python3
def main():
    c = Child(123)
    assert c.data == 123
    c.data = 'Hello'
    assert c.data == 'Hello'
    c.data += ', world!'
    assert c.data == 'Hello, world!'


class Parent:
    def __init__(self, data):
        self.__data = data

    def transform(self, transformer):
        self.__data = transformer(self.__data)


class Child(Parent):
    def __get_data(self):
        self.transform(self.__collect)
        return self.__value

    def __collect(self, value):
        self.__value = value
        return value

    def __set_data(self, value):
        self.transform(lambda data: value)

    data = property(__get_data, __set_data)


if __name__ == '__main__':
    main()

Aucun commentaire:

Enregistrer un commentaire