PHP结构型模式之享元模式详解(js享元模式)新鲜出炉

随心笔谈12个月前发布 admin
89 0

<?php
// 享元接口
interface Flyweight
{
public function operation();
}
// 具体享元类
class ConcreteFlyweight implements Flyweight
{
private $state;
public function __construct($state)
{
$this->state=$state;
}
public function operation()
{
echo “ConcreteFlyweight with state {$this->state} is operated.\n”;
}
}
// 享元工厂类
class FlyweightFactory
{
private $flyweights=[];
public function getFlyweight($state)
{
if (!isset($this->flyweights[$state])) {
$this->flyweights[$state]=new ConcreteFlyweight($state);
}
return $this->flyweights[$state];
}
}
// 客户端代码
$factory=new FlyweightFactory();
$flyweight1=$factory->getFlyweight(“state1”);
$flyweight1->operation();
$flyweight2=$factory->getFlyweight(“state2”);
$flyweight2->operation();
$flyweight3=$factory->getFlyweight(“state1”);
$flyweight3->operation();

© 版权声明

相关文章