dimanche 9 octobre 2016

Pattern for class attribute that can only be altered by others

So let's say I have a Door class and a Lock class. Instances of the Door class have a lock property that is an instance of the Lock class.

I want the door to "own" it's instance of the Lock but I don't want the door to be able to alter its own lock. For example I DONT want this to be possible:

class FancyDoor extends Door {
    function unlockMyself() {
        $this->lock->locked = false;
    }
}

But I DO want a door's lock to be accessible to other classes. For example, I need a DoorMan class to be able to lock and unlock doors. So it's not as simple as just making all of the Lock properties private.

Is there a pattern for doing this? I'm primarily working in PHP but an answer does need to be language-specific. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire