Repository: baijunyao/design-patterns
Branch: master
Commit: 577d31ba1be0
Files: 129
Total size: 80.7 KB
Directory structure:
gitextract__6eyr3aa/
├── AbstractFactory/
│ ├── Article.php
│ ├── Factory.php
│ ├── MySQLArticle.php
│ ├── MySQLFactory.php
│ ├── MySQLUser.php
│ ├── SQLiteArticle.php
│ ├── SQLiteFactory.php
│ ├── SQLiteUser.php
│ ├── User.php
│ └── index.php
├── AbstractFactoryWithReflection/
│ ├── Article.php
│ ├── Factory.php
│ ├── MySQLArticle.php
│ ├── MySQLUser.php
│ ├── SQLiteArticle.php
│ ├── SQLiteUser.php
│ ├── User.php
│ ├── config.php
│ └── index.php
├── AbstractFactoryWithSimpleFactory/
│ ├── Article.php
│ ├── Factory.php
│ ├── MySQLArticle.php
│ ├── MySQLUser.php
│ ├── SQLiteArticle.php
│ ├── SQLiteUser.php
│ ├── User.php
│ ├── config.php
│ └── index.php
├── Bridge/
│ ├── Circle.php
│ ├── Color.php
│ ├── Graph.php
│ ├── Green.php
│ ├── Red.php
│ ├── Square.php
│ ├── Triangle.php
│ ├── Yellow.php
│ └── index.php
├── ClassAdapter/
│ ├── Adaptee.php
│ ├── Adapter.php
│ ├── Target.php
│ └── index.php
├── Command/
│ ├── Command.php
│ ├── CommandInterface.php
│ ├── Invoker.php
│ ├── Receiver.php
│ └── index.php
├── Decorator/
│ ├── Decorator.php
│ ├── Egg.php
│ ├── Food.php
│ ├── Kaolengmian.php
│ ├── Latiao.php
│ ├── Sausage.php
│ ├── Shouzhuabing.php
│ └── index.php
├── Facade/
│ ├── Encrypt.php
│ ├── Facade.php
│ ├── File.php
│ └── index.php
├── FactoryMethod/
│ ├── Add.php
│ ├── AddFactory.php
│ ├── Div.php
│ ├── DivFactory.php
│ ├── Factory.php
│ ├── Mul.php
│ ├── MulFactory.php
│ ├── Operation.php
│ ├── Sub.php
│ ├── SubFactory.php
│ └── index.php
├── Flyweight/
│ ├── ConcreteFlyweight.php
│ ├── Flyweight.php
│ ├── FlyweightFactory.php
│ ├── UnsharedConcreteFlyweight.php
│ └── index.php
├── Iterator/
│ ├── ContainerInterface.php
│ ├── IteratorInterface.php
│ ├── NameContainer.php
│ ├── NameIterator.php
│ └── index.php
├── ObjectAdapter/
│ ├── Adaptee.php
│ ├── Adapter.php
│ ├── Target.php
│ └── index.php
├── Observer/
│ ├── EmailObserver.php
│ ├── Observer.php
│ ├── SMSObserver.php
│ ├── Subject.php
│ ├── SubjectAbstract.php
│ └── index.php
├── Prototype/
│ ├── Car.php
│ ├── DeepDrive.php
│ ├── ShallowDrive.php
│ └── index.php
├── Proxy/
│ ├── Proxy.php
│ ├── RealSubject.php
│ ├── Subject.php
│ └── index.php
├── SafeComposite/
│ ├── Component.php
│ ├── Dir.php
│ ├── File.php
│ └── index.php
├── SimpleFactory/
│ ├── Add.php
│ ├── Bad.php
│ ├── Div.php
│ ├── Factory.php
│ ├── Mul.php
│ ├── Operation.php
│ ├── Sub.php
│ └── index.php
├── Template/
│ ├── Huawei.php
│ ├── Phone.php
│ ├── Xiaomi.php
│ └── index.php
├── TransparentComposite/
│ ├── Component.php
│ ├── Dir.php
│ ├── File.php
│ └── index.php
├── composer.json
├── index.html
├── readme.md
├── singleton/
│ └── index.php
└── vendor/
├── autoload.php
└── composer/
├── ClassLoader.php
├── LICENSE
├── autoload_classmap.php
├── autoload_namespaces.php
├── autoload_psr4.php
├── autoload_real.php
└── autoload_static.php
================================================
FILE CONTENTS
================================================
================================================
FILE: AbstractFactory/Article.php
================================================
createUser();
$user->insert();
echo '
';
$user->select();
echo '
';
$factory = new MySQLFactory();
// 创建 article
$article = $factory->createArticle();
$article->insert();
echo '
';
$article->select();
echo '
';
// 使用 SQLite
$factory = new SQLiteFactory();
// 创建 user
$user = $factory->createUser();
$user->insert();
echo '
';
$user->select();
echo '
';
$factory = new SQLiteFactory();
// 创建 article
$article = $factory->createArticle();
$article->insert();
echo '
';
$article->select();
}
}
$client = new Client();
$client->run();
================================================
FILE: AbstractFactoryWithReflection/Article.php
================================================
db = $config['driver'];
}
/**
* 创建 User 产品
*
* @return MySQLUser|SQLiteUser
*/
public function createUser()
{
$className = $this->namespace . $this->db . 'User';
try {
$class = new ReflectionClass($className);
$user = $class->newInstance();
} catch (ReflectionException $Exception) {
throw new \InvalidArgumentException('暂不支持的数据库类型');
}
return $user;
}
/**
* 创建 Article 产品
*
* @return MySQLArticle|SQLiteArticle
*/
public function createArticle()
{
$className = $this->namespace . $this->db . 'Article';
try {
$class = new ReflectionClass($className);
$article = $class->newInstance();
} catch (ReflectionException $Exception) {
throw new \InvalidArgumentException('暂不支持的数据库类型');
}
return $article;
}
}
================================================
FILE: AbstractFactoryWithReflection/MySQLArticle.php
================================================
'SQLite'
];
================================================
FILE: AbstractFactoryWithReflection/index.php
================================================
createUser();
$user->insert();
echo '
';
$user->select();
echo '
';
// 创建 article
$article = $factory->createArticle();
$article->insert();
echo '
';
$article->select();
}
}
$client = new Client();
$client->run();
================================================
FILE: AbstractFactoryWithSimpleFactory/Article.php
================================================
db = $config['driver'];
}
/**
* 创建 User 产品
*
* @return MySQLUser|SQLiteUser
*/
public function createUser()
{
switch ($this->db) {
case 'MySQL':
$user = new MySQLUser();
break;
case 'SQLite':
$user = new SQLiteUser();
break;
default:
throw new \InvalidArgumentException('暂不支持的数据库类型');
}
return $user;
}
/**
* 创建 Article 产品
*
* @return MySQLArticle|SQLiteArticle
*/
public function createArticle()
{
switch ($this->db) {
case 'MySQL':
$article = new MySQLArticle();
break;
case 'SQLite':
$article = new SQLiteArticle();
break;
default:
throw new \InvalidArgumentException('暂不支持的数据库类型');
}
return $article;
}
}
================================================
FILE: AbstractFactoryWithSimpleFactory/MySQLArticle.php
================================================
'SQLite'
];
================================================
FILE: AbstractFactoryWithSimpleFactory/index.php
================================================
createUser();
$user->insert();
echo '
';
$user->select();
echo '
';
// 创建 article
$article = $factory->createArticle();
$article->insert();
echo '
';
$article->select();
}
}
$client = new Client();
$client->run();
================================================
FILE: Bridge/Circle.php
================================================
color->run()} 的圆形";
}
}
================================================
FILE: Bridge/Color.php
================================================
color = $color;
}
/**
* @return mixed
*/
abstract public function draw();
}
================================================
FILE: Bridge/Green.php
================================================
color->run()} 的正方形";
}
}
================================================
FILE: Bridge/Triangle.php
================================================
color->run()} 的三角形";
}
}
================================================
FILE: Bridge/Yellow.php
================================================
draw();
echo '
';
// 黄色的正方形
$yellowSquare = new Square($yellow);
$yellowSquare->draw();
echo '
';
// 绿色的正方形
$greenSquare = new Square($green);
$greenSquare->draw();
echo '
';
// 红色的三角形
$redTriangle = new Triangle($red);
$redTriangle->draw();
echo '
';
// 黄色的三角形
$yellowTriangle = new Triangle($yellow);
$yellowTriangle->draw();
echo '
';
// 绿色的三角形
$greenTriangle = new Triangle($green);
$greenTriangle->draw();
echo '
';
// 红色的圆形
$redCircle = new Circle($red);
$redCircle->draw();
echo '
';
// 黄色的圆形
$yellowCircle = new Circle($yellow);
$yellowCircle->draw();
echo '
';
// 绿色的圆形
$greenCircle = new Circle($green);
$greenCircle->draw();
echo '
';
}
}
$client = new Client();
$client->run();
================================================
FILE: ClassAdapter/Adaptee.php
================================================
money;
}
}
================================================
FILE: ClassAdapter/Adapter.php
================================================
money = '$5';
}
/**
* 通知
*/
public function notify()
{
echo '通知';
}
}
================================================
FILE: ClassAdapter/Target.php
================================================
pay();
echo '
';
// 适配器
$adapter = new Adapter();
$adapter->pay();
echo '
';
$adapter->notify();
}
}
$client = new Client();
$client->run();
================================================
FILE: Command/Command.php
================================================
receiver = $receiver;
}
/**
* @return mixed|void
*/
public function execute()
{
$this->receiver->action();
}
}
================================================
FILE: Command/CommandInterface.php
================================================
command = $command;
}
/**
* 执行
*/
public function run()
{
$this->command->execute();
}
}
================================================
FILE: Command/Receiver.php
================================================
setCommand($command);
$invoker->run();
}
}
$client = new Client();
$client->run();
================================================
FILE: Decorator/Decorator.php
================================================
food = $food;
}
}
================================================
FILE: Decorator/Egg.php
================================================
food->name() . '+蛋';
}
/**
* 价格
*
* @return int|mixed
*/
public function price()
{
return $this->food->price() + 1;
}
}
================================================
FILE: Decorator/Food.php
================================================
food->name() . '+辣条';
}
/**
* 价格
*
* @return int|mixed
*/
public function price()
{
return $this->food->price() + 3;
}
}
================================================
FILE: Decorator/Sausage.php
================================================
food->name() . '+肠';
}
/**
* 价格
*
* @return int|mixed
*/
public function price()
{
return $this->food->price() + 2;
}
}
================================================
FILE: Decorator/Shouzhuabing.php
================================================
name();
echo $shouzhuabing->price() . '元';
echo '
';
// 烤冷面
$kaolengmian = new Kaolengmian();
echo $kaolengmian->name();
echo $kaolengmian->price() . '元';
echo '
';
// 手抓饼+蛋
$egg = new Egg($shouzhuabing);
echo $egg->name();
echo $egg->price() . '元';
echo '
';
// 手抓饼+肠
$sausage = new Sausage($kaolengmian);
echo $sausage->name();
echo $sausage->price() . '元';
echo '
';
// 烤冷面+辣条
$latiao = new Latiao($shouzhuabing);
echo $latiao->name();
echo $latiao->price() . '元';
echo '
';
}
}
$client = new Client();
$client->run();
================================================
FILE: Facade/Encrypt.php
================================================
file = new File();
$this->encrypt = new Encrypt();
}
/**
* 获取文件内容并加密
*/
public function encryptContent()
{
echo $this->file->content();
echo '
';
echo $this->encrypt->encrypt();
}
}
================================================
FILE: Facade/File.php
================================================
encryptContent();
}
}
$client = new Client();
$client->run();
================================================
FILE: FactoryMethod/Add.php
================================================
numberA + $this->numberB;
}
}
================================================
FILE: FactoryMethod/AddFactory.php
================================================
numberB == 0) {
throw new \InvalidArgumentException('除数不能为0');
}
return $this->numberA / $this->numberB;
}
}
================================================
FILE: FactoryMethod/DivFactory.php
================================================
numberA * $this->numberB;
}
}
================================================
FILE: FactoryMethod/MulFactory.php
================================================
numberA = $number;
}
/**
* 给 numberB 赋值
*
* @param $number
*/
public function setNumberB($number)
{
$this->numberB = $number;
}
}
================================================
FILE: FactoryMethod/Sub.php
================================================
numberA - $this->numberB;
}
}
================================================
FILE: FactoryMethod/SubFactory.php
================================================
setNumberA(1);
$operation->setNumberB(2);
$result = $operation->getResult();
echo $result;
echo '
';
// 计算 3+4
$operation = new Add();
$operation->setNumberA(3);
$operation->setNumberB(4);
$result = $operation->getResult();
echo $result;
}
/**
* 好的示例 new 产品对应的工厂
*/
public function good()
{
$factory = new AddFactory();
$operation = $factory->create();
$operation->setNumberA(1);
$operation->setNumberB(2);
$result = $operation->getResult();
echo $result;
}
}
$client = new Client();
$client->bad();
echo '
';
$client->good();
================================================
FILE: Flyweight/ConcreteFlyweight.php
================================================
name . $content . '
';
}
}
================================================
FILE: Flyweight/Flyweight.php
================================================
name = $name;
}
/**
* @param $content
*/
public function show($content){}
}
================================================
FILE: Flyweight/FlyweightFactory.php
================================================
flyweights[$name])){
$this->flyweights[$name]=new ConcreteFlyweight($name);
}
return $this->flyweights[$name];
}
}
================================================
FILE: Flyweight/UnsharedConcreteFlyweight.php
================================================
name . $content . '
';
}
/**
* 附加的删除方法
*/
public function delete()
{
$this->name = '';
}
}
================================================
FILE: Flyweight/index.php
================================================
getFlyweight('170cm的模特');
$zhangsan1->show('第1件L号的衣服');
$zhangsan2 = $flyweight->getFlyweight('170cm的模特');
$zhangsan2->show('第99件L号的衣服');
var_dump($zhangsan1 === $zhangsan2);
echo '
';
$lisi = $flyweight->getFlyweight('180cm的模特');
$lisi->show('第1件XXL号的衣服');
$wangmazi = new UnsharedConcreteFlyweight('190cm的模特');
$wangmazi->show('第1件XXXL号的衣服');
$wangmazi->delete();
$wangmazi->show('第1件XXXL号的衣服');
}
}
$client = new Client();
$client->run();
================================================
FILE: Iterator/ContainerInterface.php
================================================
nameArray[] = $name;
}
/**
* 获取迭代器
*
* @return \Baijunyao\DesignPatterns\Iterator\NameIterator|mixed
*/
public function getIterator()
{
return new NameIterator($this->nameArray);
}
}
================================================
FILE: Iterator/NameIterator.php
================================================
nameArray = $nameArray;
}
/**
* 判断是否还有下一个姓名
*
* @return bool|mixed
*/
public function hasNext()
{
return $this->index < count($this->nameArray);
}
/**
* 下一个姓名
*
* @return mixed|void
*/
public function next()
{
if ($this->hasNext()) {
echo $this->nameArray[$this->index] . '
';
$this->index++;
}
}
}
================================================
FILE: Iterator/index.php
================================================
add('张三');
$nameContainer->add('李四');
$nameContainer->add('王麻子');
$nameIterator = $nameContainer->getIterator();
while ($nameIterator->hasNext()) {
echo $nameIterator->next();
}
}
}
$client = new Client();
$client->run();
================================================
FILE: ObjectAdapter/Adaptee.php
================================================
money;
}
}
================================================
FILE: ObjectAdapter/Adapter.php
================================================
adaptee = $adaptee;
$adaptee->money = '$5';
}
/**
* 支付
*
* @return mixed|void
*/
public function pay()
{
$this->adaptee->pay();
}
/**
* 通知
*
* @return mixed|void
*/
public function notify()
{
echo '通知';
}
}
================================================
FILE: ObjectAdapter/Target.php
================================================
pay();
echo '
';
// 适配器
$adapter = new Adapter($adaptee);
$adapter->pay();
echo '
';
$adapter->notify();
}
}
$client = new Client();
$client->run();
================================================
FILE: Observer/EmailObserver.php
================================================
';
}
}
================================================
FILE: Observer/Observer.php
================================================
';
}
}
================================================
FILE: Observer/Subject.php
================================================
';
$this->notify();
}
}
================================================
FILE: Observer/SubjectAbstract.php
================================================
observers[] = $observer;
}
/**
* 通知
*/
public function notify()
{
foreach ($this->observers as $k => $v) {
$v->update();
}
}
}
================================================
FILE: Observer/index.php
================================================
attach($emailObserver);
$subject->attach($SMSObserver);
$subject->publish();
}
}
$client = new Client();
$client->run();
================================================
FILE: Prototype/Car.php
================================================
name = $name;
}
}
================================================
FILE: Prototype/DeepDrive.php
================================================
car = $car;
}
public function show()
{
echo '开始驾驶'.$this->car->name;
echo '
';
}
public function __clone()
{
$this->car = clone $this->car;
}
}
================================================
FILE: Prototype/ShallowDrive.php
================================================
car = $car;
}
public function show()
{
echo '开始驾驶'.$this->car->name;
echo '
';
}
}
================================================
FILE: Prototype/index.php
================================================
name = '特斯拉';
$shallowDrive = new ShallowDrive();
$shallowDrive->setCar($car);
$shallowDrive->show();
$cloneDrive = clone $shallowDrive;
$cloneDrive->show();
echo '
';
$car->name = '凯迪拉克';
$shallowDrive->show();
$cloneDrive->show();
}
/**
*
*/
public function deepCopy()
{
$car = new Car();
$car->name = '特斯拉';
$deepDrive = new DeepDrive();
$deepDrive->setCar($car);
$deepDrive->show();
$cloneDrive = clone $deepDrive;
$cloneDrive->show();
echo '
';
$car->name = '凯迪拉克';
$deepDrive->show();
$cloneDrive->show();
}
}
$client = new Client();
$client->shallowCopy();
echo '
-----------------------------
';
$client->deepCopy();
================================================
FILE: Proxy/Proxy.php
================================================
realSubject = new RealSubject();
}
/*
* 执行操作
*/
public function action()
{
$this->realSubject->action();
}
}
================================================
FILE: Proxy/RealSubject.php
================================================
action();
}
}
$client = new Client();
$client->run();
================================================
FILE: SafeComposite/Component.php
================================================
name = $name;
}
/**
* @return mixed
*/
abstract public function display();
}
================================================
FILE: SafeComposite/Dir.php
================================================
children[] = $component;
}
/**
* @return mixed|string
*/
public function display()
{
$nameStr = $this->name .'
';
foreach ($this->children as $k => $v) {
$nameStr .= '--' . $v->display();
}
return $nameStr;
}
}
================================================
FILE: SafeComposite/File.php
================================================
name .'
';
}
}
================================================
FILE: SafeComposite/index.php
================================================
add($classAdapter);
$designPatterns->add($objectAdapter);
$designPatterns->add($safeComposite);
$componentFile = new File('Component.php');
$dirFile = new File('Dir.php');
$fileFile = new File('File.php');
$indexFile = new File('index.php');
$safeComposite->add($componentFile);
$safeComposite->add($dirFile);
$safeComposite->add($fileFile);
$safeComposite->add($indexFile);
echo $designPatterns->display();
}
}
$client = new Client();
$client->run();
================================================
FILE: SimpleFactory/Add.php
================================================
numberA + $this->numberB;
}
}
================================================
FILE: SimpleFactory/Bad.php
================================================
numberB == 0) {
throw new \InvalidArgumentException('除数不能为0');
}
return $this->numberA / $this->numberB;
}
}
================================================
FILE: SimpleFactory/Factory.php
================================================
numberA * $this->numberB;
}
}
================================================
FILE: SimpleFactory/Operation.php
================================================
numberA = $number;
}
/**
* 给 numberB 赋值
*
* @param $number
*/
public function setNumberB($number)
{
$this->numberB = $number;
}
}
================================================
FILE: SimpleFactory/Sub.php
================================================
numberA - $this->numberB;
}
}
================================================
FILE: SimpleFactory/index.php
================================================
getResult(1, '+', 2);
echo $result;
}
/**
* 不好的示例2
*
* @return int
*/
public function bad2()
{
// 计算 1+2
$operation = new Add();
$operation->setNumberA(1);
$operation->setNumberB(2);
$result = $operation->getResult();
echo $result;
echo '
';
// 计算 3+4
$operation = new Add();
$operation->setNumberA(3);
$operation->setNumberB(4);
$result = $operation->getResult();
echo $result;
}
/**
* 好的示例
*/
public function good()
{
$factory = new Factory();
$operation = $factory->create('+');
$operation->setNumberA(1);
$operation->setNumberB(2);
$result = $operation->getResult();
echo $result;
}
}
$client = new Client();
$client->bad();
echo '
';
$client->bad2();
echo '
';
$client->good();
================================================
FILE: Template/Huawei.php
================================================
';
}
}
================================================
FILE: Template/Phone.php
================================================
powerOn();
$this->showLogo();
$this->callUp();
}
/**
* 开机
*/
protected function powerOn()
{
echo '开机' . '
';
}
/**
* logo
*
* @return mixed
*/
abstract protected function showLogo();
/**
* 打电话
*/
protected function callUp()
{
echo '打电话' . '
';
}
}
================================================
FILE: Template/Xiaomi.php
================================================
';
}
}
================================================
FILE: Template/index.php
================================================
action();
echo '
';
$huawei = new Huawei();
$huawei->action();
}
}
$client = new Client();
$client->run();
================================================
FILE: TransparentComposite/Component.php
================================================
name = $name;
}
/**
* 添加子节点
*
* @return mixed
*/
abstract public function add();
/**
* 展示名称
*
* @return mixed
*/
abstract public function display();
}
================================================
FILE: TransparentComposite/Dir.php
================================================
children[] = $component;
}
/**
* @return mixed|string
*/
public function display()
{
$nameStr = $this->name .'
';
foreach ($this->children as $k => $v) {
$nameStr .= '--' . $v->display();
}
return $nameStr;
}
}
================================================
FILE: TransparentComposite/File.php
================================================
name .'
';
}
}
================================================
FILE: TransparentComposite/index.php
================================================
add($classAdapter);
$designPatterns->add($objectAdapter);
$designPatterns->add($transparentComposite);
$componentFile = new File('Component.php');
$dirFile = new File('Dir.php');
$fileFile = new File('File.php');
$indexFile = new File('index.php');
$transparentComposite->add($componentFile);
$transparentComposite->add($dirFile);
$transparentComposite->add($fileFile);
$transparentComposite->add($indexFile);
echo $designPatterns->display();
}
}
$client = new Client();
$client->run();
================================================
FILE: composer.json
================================================
{
"name": "baijunyao/design-patterns",
"description": "design patterns",
"type": "project",
"license": "MIT",
"authors": [
{
"name": "baijunyao",
"email": "baijunyao@baijunyao.com"
}
],
"require": {},
"autoload": {
"psr-4": {
"Baijunyao\\DesignPatterns\\": ""
}
}
}
================================================
FILE: index.html
================================================
设计模式-白俊遥
文章
- php设计模式(一)序言
- php设计模式(二)单例模式
- php设计模式(三)简单工厂模式
- php设计模式(四)工厂方法模式
- php设计模式(五)抽象工厂模式
- php设计模式(六)使用简单工厂来优化抽象工厂模式
- php设计模式(七)使用反射来优化抽象工厂模式
- php设计模式(八)原型模式
- php设计模式(九)类适配器模式
- php设计模式(十)对象适配器模式
- php设计模式(十一)桥接模式
- php设计模式(十二)装饰模式
- php设计模式(十三)透明组合模式
- php设计模式(十四)安全组合模式
- php设计模式(十五)外观模式
- php设计模式(十六)享元模式
- php设计模式(十七)代理模式
- php设计模式(十八)代理模式
- php设计模式(十九)命令模式
- php设计模式(二十)迭代器模式
- php设计模式(二十一)观察者模式
目录
================================================
FILE: readme.md
================================================
### 文章
1. [php设计模式(一)序言](https://baijunyao.com/article/158)
2. [php设计模式(二)单例模式](https://baijunyao.com/article/159)
3. [php设计模式(三)简单工厂模式](https://baijunyao.com/article/161)
4. [php设计模式(四)工厂方法模式](https://baijunyao.com/article/162)
5. [php设计模式(五)抽象工厂模式](https://baijunyao.com/article/164)
6. [php设计模式(六)使用简单工厂来优化抽象工厂模式](https://baijunyao.com/article/165)
7. [php设计模式(七)使用反射来优化抽象工厂模式](https://baijunyao.com/article/166)
8. [php设计模式(八)原型模式](https://baijunyao.com/article/167)
9. [php设计模式(九)类适配器模式](https://baijunyao.com/article/168)
10. [php设计模式(十)对象适配器模式](https://baijunyao.com/article/169)
11. [php设计模式(十一)桥接模式](https://baijunyao.com/article/170)
12. [php设计模式(十二)装饰模式](https://baijunyao.com/article/172)
13. [php设计模式(十三)透明组合模式](https://baijunyao.com/article/174)
14. [php设计模式(十四)安全组合模式](https://baijunyao.com/article/175)
15. [php设计模式(十五)外观模式](https://baijunyao.com/article/176)
16. [php设计模式(十六)享元模式](https://baijunyao.com/article/177)
17. [php设计模式(十七)代理模式](https://baijunyao.com/article/178)
18. [php设计模式(十八)模板方法模式](https://baijunyao.com/article/179)
19. [php设计模式(十九)命令模式](https://baijunyao.com/article/182)
20. [php设计模式(二十)迭代器模式](https://baijunyao.com/article/183)
21. [php设计模式(二十一)观察者模式](https://baijunyao.com/article/184)
### 目录
- [单例模式](https://github.com/baijunyao/design-patterns/tree/master/singleton)
- [简单工厂模式](https://github.com/baijunyao/design-patterns/tree/master/SimpleFactory)
- [工厂方法模式](https://github.com/baijunyao/design-patterns/tree/master/FactoryMethod)
- [抽象工厂模式](https://github.com/baijunyao/design-patterns/tree/master/AbstractFactory)
- [使用简单工厂来优化抽象工厂模式](https://github.com/baijunyao/design-patterns/tree/master/AbstractFactoryWithSimpleFactory)
- [使用反射来优化抽象工厂模式](https://github.com/baijunyao/design-patterns/tree/master/AbstractFactoryWithReflection)
- [原型模式](https://github.com/baijunyao/design-patterns/tree/master/Prototype)
- [类适配器模式](https://github.com/baijunyao/design-patterns/tree/master/ClassAdapter)
- [对象适配器模式](https://github.com/baijunyao/design-patterns/tree/master/ObjectAdapter)
- [桥接模式](https://github.com/baijunyao/design-patterns/tree/master/Bridge)
- [装饰模式](https://github.com/baijunyao/design-patterns/tree/master/Decorator)
- [透明组合模式](https://github.com/baijunyao/design-patterns/tree/master/TransparentComposite)
- [安全组合模式](https://github.com/baijunyao/design-patterns/tree/master/SafeComposite)
- [外观模式](https://github.com/baijunyao/design-patterns/tree/master/Facade)
- [享元模式](https://github.com/baijunyao/design-patterns/tree/master/Flyweight)
- [代理模式](https://github.com/baijunyao/design-patterns/tree/master/Proxy)
- [模板方法模式](https://github.com/baijunyao/design-patterns/tree/master/Template)
- [命令模式](https://github.com/baijunyao/design-patterns/tree/master/Command)
- [迭代器模式](https://github.com/baijunyao/design-patterns/tree/master/Iterator)
- [观察者模式](https://github.com/baijunyao/design-patterns/tree/master/Observer)
================================================
FILE: singleton/index.php
================================================
';
var_dump($db2);
echo '
';
var_dump($db3);
echo '
';
var_dump($db4);
echo '
';
var_dump($db5);
echo '
';
/**
* 单例
*
* Class Db2
* @package Baijunyao\DesignPatterns\Singleton
*/
class Db2
{
private static $instance = null;
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
/**
* 防止使用 new 创建多个实例
*
* Db2 constructor.
*/
private function __construct()
{
}
/**
* 防止 clone 多个实例
*/
private function __clone()
{
}
/**
* 防止反序列化
*/
private function __wakeup()
{
}
}
$db6 = Db2::getInstance();
$db7 = Db2::getInstance();
var_dump($db6);
echo '
';
var_dump($db7);
echo '
';
================================================
FILE: vendor/autoload.php
================================================
* Jordi Boggiano
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier
* @author Jordi Boggiano
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}
================================================
FILE: vendor/composer/LICENSE
================================================
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: vendor/composer/autoload_classmap.php
================================================
array($baseDir . '/'),
);
================================================
FILE: vendor/composer/autoload_real.php
================================================
= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit88798c90f3cb8871fa59cc0f15b5142f::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
return $loader;
}
}
================================================
FILE: vendor/composer/autoload_static.php
================================================
array (
'Baijunyao\\DesignPatterns\\' => 25,
),
);
public static $prefixDirsPsr4 = array (
'Baijunyao\\DesignPatterns\\' =>
array (
0 => __DIR__ . '/../..' . '/',
),
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit88798c90f3cb8871fa59cc0f15b5142f::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit88798c90f3cb8871fa59cc0f15b5142f::$prefixDirsPsr4;
}, null, ClassLoader::class);
}
}