修改另一个插槽时更新插槽

CLOS MOP 提供了 hook slot-value-using-class,当访问,读取或修改插槽值时调用它。因为在这种情况下我们只关心修改,所以我们为 (setf slot-value-using-class) 定义了一个方法。

(defclass document ()
  ((id :reader id :documentation "A hash computed with the contents of every other slot")
   (title :initarg :title :accessor title)
   (body :initarg :body :accessor body)))

(defmethod (setf c2mop:slot-value-using-class) :after
    (new class (object document) (slot c2mop:standard-effective-slot-definition))
  ;; To avoid this method triggering a call to itself, we check that the slot
  ;; the modification occurred in is not the slot we are updating.
  (unless (eq (slot-definition-name slot) 'id)
    (setf (slot-value object 'id) (hash-slots object))))

请注意,因为在实例创建时没有调用 slot-value,所以可能需要在 initialize-instance :after 方法中复制代码

(defmethod initialize-instance :after ((obj document) &key)
  (setf (slot-value obj 'id)
        (hash-slots obj)))