Value Model

Motivation

A Value Model is an Adapter class extracting a single value from an adaptee (SubModel).
The extracted value is exposed thought a uniform and trivial interface: a getter
ValueModel.value(), a setter ValueModel.set_value(), and notification.

Views and Controllers using a Value Model can be extremely simple and
off-the-shelf, provided that they can handle the Value Model interface.
They can ignore the nature of the adapted SubModel, leaving to the Value
Model the responsibility of taking care of the details.

Design

The Value Model class acts as an adapter


Value Model - 图1

A trivial implementation of a Value Model would be:

  1. class ValueModel(Model):
  2. def __init__(self, sub_model):
  3. self._sub_model = sub_model
  4. def set_value(self, value):
  5. # do potentially complex logic on self._sub_model
  6. # to appropriately manipulate the passed value
  7. # This method triggers a self.value_changed notification.
  8. def value(self):
  9. # do potentially complex logic on self._sub_model
  10. # to extract a single value

Many different Value Model classes can be implemented, each one
adapting a different SubModel, or operating over different parts of a SubModel.
Views and Controllers interact with the Value Models through the minimalist interface,
and are therefore agnostic of the Value Model used.

Practical Example

One could adapt a Customer object through two Value Models: NameValueModel and SurnameValueModel.

  1. class NameValueModel(Model):
  2. def __init__(self, customer):
  3. self._customer = customer
  4. def set_value(self, value):
  5. self._customer.name = value
  6. self.notify_observers()
  7. def value(self):
  8. return self._customer.name
  9. class SurnameValueModel(Model):
  10. def __init__(self, customer):
  11. self._customer = customer
  12. def set_value(self, value):
  13. self._customer.surname = value
  14. self.notify_observers()
  15. def value(self):
  16. return self._customer.surname

Each of these two ValueModels can use an off-the-shelf
StringWidget View, agnostic of the actual nature of the
Customer model and retrieving/modifying data through the
Value Model interface.