<?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();
// 享元接口
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();
© 版权声明
文章版权归作者所有,未经允许请勿转载。