-
Notifications
You must be signed in to change notification settings - Fork 50
/
sharePool.php
52 lines (51 loc) · 1.2 KB
/
sharePool.php
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
44
45
46
47
48
49
50
51
52
<?php
/**
* @Author: lock
* @Date: 2017-02-14 09:32:15
* @Last Modified by: lock
* @Last Modified time: 2017-02-14 09:32:28
*/
//抽象享元角色
interface Flyweight{
function show();
}
//共享的具体享元角色
class ConcreteFlyweight implements Flyweight{
private $state;
function __construct($state){
$this->state = $state;
}
function show(){
return $this->state;
}
}
//不共享的具体享元角色,客户端直接调用
class UnsharedConcreteFlyweight implements Flyweight{
private $state;
function __construct($state){
$this->state = $state;
}
function show(){
return $this->state;
}
}
//享元工厂模式
class FlyweightFactory{
private $flyweights = array();
function getFlyweight($state){
if(!isset($this->flyweights[$state])){
$this->flyweights[$state]=new ConcreteFlyweight($state);
}
return $this->flyweights[$state];
}
}
//测试
$flyweightFactory = new FlyweightFactory();
$flyweightOne = $flyweightFactory->getFlyweight("state A");
echo $flyweightOne->show();
$flyweightTwo = new UnsharedConcreteFlyweight("state B");
echo $flyweightTwo->show();
/*
state A
state B
*/