<?php
//策略模式
interface OutputInterface
{
public function load($arrayOfData);
}
class SerializedArrayOutput implements OutputInterface
{
public function load($arrayOfData)
{
return serialize($arrayOfData);
}
}
class JsonStringOutput implements OutputInterface
{
public function load($arrayOfData)
{
return json_encode($arrayOfData);
}
}
class ArrayOutput implements OutputInterface
{
public function load($arrayOfData)
{
return $arrayOfData;
}
}
class SomeClient
{
private $output;
public function setOutput(OutputInterface $outputType)
{
$this->output = $outputType;
}
public function loadOutput($arrayOfData)
{
return $this->output->load($arrayOfData);
}
}
$client = new SomeClient();
$arrayOfData = array('name'=>'action','age'=>'28');
// Want an array?
$client->setOutput(new ArrayOutput());
$data = $client->loadOutput($arrayOfData);
var_dump($data);
echo "<hr>";
// Want some JSON?
$client->setOutput(new JsonStringOutput());
$data = $client->loadOutput($arrayOfData);
var_dump($data);
echo "<hr>";
// Want some Serialized?
$client->setOutput(new SerializedArrayOutput());
$data = $client->loadOutput($arrayOfData);
var_dump($data);
action
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0授权协议,
转载请注明来源,谢谢!如本站内容对你有所帮助的话,欢迎订阅关注
邢栋博客,唠嗑(分享)每日的折腾经历。
已有 0 条评论