下面的代码(取自以下葡萄牙语页面http://br.phptherightway.com/pages/Design-Patterns.html)展示了策略的使用。我的问题是如何从ArrayOutput加载()方法可以返回$arrayOfData,如果它没有定义?
interface OutputInterface{
public function load();
}
class ArrayOutput implements OutputInterface{
public function load() {
return $arrayOfData;
}
}
class SomeClient{
private $output;
public function setOutput(OutputInterface $outputType){
$this->output = $outputType;
}
public function loadOutput(){
return $this->output->load();
}
}
$client = new SomeClient();
// Array
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();
请看下面的代码
interface OutputInterface{
public function load();
}
class ArrayOutput implements OutputInterface{
public function load() {
if (empty ($arrayOfData))
{
return null; //if the $arrayOfData is empty then it will return an empty response i.e null
}
return $arrayOfData;
}
}
class SomeClient{
private $output;
public function setOutput(OutputInterface $outputType){
$this->output = $outputType;
}
public function loadOutput(){
return $this->output->load();
}
}
$client = new SomeClient();
// Array
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput();
不能。这里的代码看起来更像是让您了解如何实现该模式的东西。它应该是这样的:
interface OutputInterface {
public function load();
}
class ArrayOutput implements OutputInterface {
private $arrayOfData;
function __construct($array) {
$this->arrayOfData = $array;
}
public function load() {
return $this->arrayOfData;
}
}