喜迎
春节

设计模式——享元模式


说明

享元模式的主要目的是实现对象的共享,即共享池,当系统中对象多的时候可以减少内存的开销,通常与工厂模式一起使用。
FlyWeightFactory负责创建和管理享元单元,当一个客户端请求时,工厂需要检查当前对象池中是否有符合条件的对象,如果有,就返回已经存在的对象,如果没有,则创建一个新对象,FlyWeight是超类。一提到共享池,我们很容易联想到Java里面的JDBC连接池,想想每个连接的特点,我们不难总结出:适用于作共享的一些个对象,他们有一些共有的属性,就拿数据库连接池来说,url、driverClassName、username、password及dbname,这些属性对于每个连接来说都是一样的,所以就适合用享元模式来处理,建一个工厂类,将上述类似属性作为内部数据,其它的作为外部数据,在方法调用时,当做参数传进来,这样就节省了空间,减少了实例的数量。

示例

下面看下享元模式的代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class ConnectionPool{
private array $pool;

private string $server = '127.0.0.1';
private string $username = 'root';
private string $password = 'root';
private string $database = 'test';

private int $poolSize = 100;
private static ?ConnectionPool $instance = null;

public $conn = null;

public function __construct(){
$this->pool = [];
for ($i=0; $i<$this->poolSize; $i++){
try {
$mysqlConn = mysqli_connect($this->server, $this->username, $this->password);
if (!$mysqlConn) die("connect error");
mysqli_select_db($mysqlConn,$this->database);
mysqli_query($mysqlConn,'SET NAMES utf8');
$this->pool[] = $mysqlConn;
}catch (Exception $e){
die("connect error");
}
}
}

public function getConnection(){
if (count($this->pool) > 0){
$this->conn = array_shift($this->pool);
return $this->conn;
}else{
return null;
}
}
}

$connPool = new ConnectionPool();
$conn1 = $connPool->getConnection();
$conn2 = $connPool->getConnection();
var_dump($conn1===$conn2); class ConnectionPool{
private array $pool;

private string $server = '127.0.0.1';
private string $username = 'root';
private string $password = 'root';
private string $database = 'test';

private int $poolSize = 100;
private static ?ConnectionPool $instance = null;

public $conn = null;

public function __construct(){
$this->pool = [];
for ($i=0; $i<$this->poolSize; $i++){
try {
$mysqlConn = mysqli_connect($this->server, $this->username, $this->password);
if (!$mysqlConn) die("connect error");
mysqli_select_db($mysqlConn,$this->database);
mysqli_query($mysqlConn,'SET NAMES utf8');
$this->pool[] = $mysqlConn;
}catch (Exception $e){
die("connect error");
}
}
}

public function getConnection(){
if (count($this->pool) > 0){
$this->conn = array_shift($this->pool);
return $this->conn;
}else{
return null;
}
}
}

$connPool = new ConnectionPool();
$conn1 = $connPool->getConnection();
$conn2 = $connPool->getConnection();
var_dump($conn1===$conn2); //false

总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
评 论
 上一篇
设计模式——中介者模式
设计模式——中介者模式
说明示例下面看下中介者模式的代码实现 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
2022-05-19
下一篇 
设计模式——代理模式
设计模式——代理模式
说明其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你做,此处的代理就是这个意思。再如我们
2022-05-19
  目录