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

随心笔谈2年前发布 编辑
150 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();

© 版权声明

相关文章