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 PHP dependent. Before it knows to Quack a duck has to Learn.

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


No, that does not violate any OOP principle.

A prominent example is an object who's behavior depends on whether a connection is established or not (eg function doNetworkStuff() depends on openConnection() ).

In Java, there is even a typestate checker, which performs such checks (whether Duck can already Quack() ) at compile time. I often have such dependencies as preconditions for interfaces, and use a forwarding class whose sole purpose is protocolling and checking the state of the object it forwards to, ie protocol which functions have been called on the object, and throw exceptions (eg InvalidStateException) when the preconditions are not met.

A design pattern that handles this is state: It allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The design pattern book from the Gang of Four also uses the example above of a network connection either being established or not.


如果你想修改顺序,那么你可以使用抽象基类,在函数quack()中你先调用learn(),然后抽象方法doquack()(一些其他的好名字,这将必须由每个派生类)。


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

you can separate concerns:

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;
  }
}

It's my first lines in PHP, feel free to correct

链接地址: http://www.djcxy.com/p/54868.html

上一篇: 使用Windows Azure工具,为什么我会收到对内存位置的无效访问?

下一篇: 对象内的依赖关系