1

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.

emersonthis
  • 32,822
  • 59
  • 210
  • 375

1 Answers1

0

I am assuming your concern is that, once FancyDoor has been coded without an unlockMyself method, some developer in future can inadvertently add it and screw the contract.

Avoiding this would be very difficult if the lock is owned by Door, given the very nature of classes. I can think of the following:

  • Door doesn't have a lock instance.
  • Lock is modeled as a separate class. You can use State Pattern for it, because:
    • You might want to add more states, apart from lock and unlock, in future.
    • The same class can be reused to work with, say, Windows in future. It needn't be tied with Doors.
  • A DoorManager or something that is composed of these two objects. This class exposes methods for locking/unlocking the Door instance that it has.

Essentially, DoorManager is responsible for one Door, and the Lock associated with it.

ketan vijayvargiya
  • 5,409
  • 1
  • 21
  • 34
  • Right. This is what I'm doing now, but it's a big clunky because I always have to pass the Door and the Lock together and the manager has to keep track of whose is whose. – emersonthis Oct 10 '16 at 14:56
  • Put both of them in one class and pass object of that class around, rather than passing both of them separately. – ketan vijayvargiya Oct 10 '16 at 18:03