位置:首页  >   程序积累  > php设计模式之策略模式简单事例

php设计模式之策略模式简单事例

<?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);

文章属性
精彩评论