8000 add flyweight file · sockstack/design-patterns-by-php@b48840b · GitHub
[go: up one dir, main page]

Skip to content

Commit b48840b

Browse files
author
Hu Lin
committed
add flyweight file
1 parent a20d397 commit b48840b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

codes/Flyweight.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
abstract class Flyweight
4+
{
5+
abstract public function operation($extringsicState);
6+
}
7+
8+
class ConcreteFlyweight extends Flyweight
9+
{
10+
public function operation($extringsicState)
11+
{
12+
echo "ConcreteFlyweight:".$extringsicState."\n";
13+
}
14+
}
15+
16+
class UnsharedConcreteFlyweight extends Flyweight
17+
{
18+
public function operation($extringsicState)
19+
{
20+
echo "Unshared ConcreteFlyweight:".$extringsicState."\n";
21+
}
22+
}
23+
24+
class FlyweightFactory
25+
{
26+
private $flyweights = [];
27+
28+
function __construct()
29+
{
30+
$this->flyweights['x'] = new ConcreteFlyweight();
31+
$this->flyweights['y'] = new ConcreteFlyweight();
32+
$this->flyweights['z'] = new ConcreteFlyweight();
33+
}
34+
35+
public function getFlyweight($key)
36+
{
37+
return $this->flyweights[$key];
38+
}
39+
}
40+
41+
//client
42+
43+
$state = 22;
44+
$f = new FlyweightFactory();
45+
$fx = $f->getFlyweight('x');
46+
$fx->operation(--$state);
47+
48+
$fx = $f->getFlyweight('y');
49+
$fx->operation(--$state);
50+
51+
$fx = $f->getFlyweight('z');
52+
$fx->operation(--$state);
53+
54+
$uf = new UnsharedConcreteFlyweight();
55+
$uf->operation(--$state);

0 commit comments

Comments
 (0)
0