Dependencies Inside an Object

I have this code

  class duck {
   protected $ strVocabulary;
   public function Learn () {
    $ this-> strVocabulary = 'quack';
   }

   public function Quack () {
    echo $ this-> strVocabulary;
   }
 }

The code is in PHP, but the question is not dependent on PHP. Before he finds out what to bite, a duck must learn.

My question is: how do I make Quack() invokable only after Learn() been called?

+7
source share
3 answers

No, this does not violate the OOP principle.

An important example is an object whose behavior depends on whether the connection is established or not (for example, the doNetworkStuff() function depends on openConnection() ).

In Java, there is even a typestate checker that performs such checks (whether Duck already Quack() ) compile time. I often have dependencies such as prerequisites for interfaces, and I use the redirect class, whose sole purpose is to log and check the state of the object to which it forwards, i.e. A protocol whose functions were called on the object, and an exception exception (for example, InvalidStateException) when the preconditions are not met.

The design pattern that handles this is state : it allows an object to change its behavior when its internal state changes. It looks like the object will change its class. The model book from Gang of Four also uses the above example of a steady network connection.

+3
source

If you want to fix the order, you can use an abstract base class, where in the quack () function, you first call learn () and then the abstract doquack () method (another good name, and this should be implemented by each derived class).

+1
source

My question is: how to make Quack () invokable only after Learn () has been called?

you can share the problems:

 class EnrolleeDuck { public function Learn() { return new AlumnusDuck('quack'); } } class AlumnusDuck { protected $strVocabulary; public function __construct(&strVocabulary) { &this->strVocabulary = &strVocabulary; } public function Quack() { echo $this->strVocabulary; } } 

These are my first lines in PHP, feel free to fix

0
source

All Articles