php中的设计模式---工厂模式及单例模式

这两个练习放在一起处理。

在python中,这些模式都有的。

要记得三大类模式:创建型,结构型,行为型。

NotFoundException.php

<?php

namespace Bookstore\Exceptions;

use Exception;

class NotFoundException extends Exception {
    
}
?>

CustomerFactory.php

<?php
namespace Bookstore\Domain;

use Bookstore\Domain\Customer;
use Exception;
//又要记得这里的不得已,如果文件结构不按namespace组织,就要手工导入.
//basic及premium这两行,抵消了工厂模式的优势了.:()
require_once __DIR__ . '/Customer.php';
require_once __DIR__ . '/Basic.php';
require_once __DIR__ . '/Premium.php';

class CustomerFactory {
    public static function factory(
        string $type,
        int $id,
        string $firstname,
        string $surname,
        string $email
    ): Customer {
        /*这种写法,太个性,每次有新的分类,都要来这里更改
        switch ($type) {
            case 'basic':
                return new Basic($id, $firstname, $surname, $email);
            case 'premium':
                return new Basic($id, $firstname, $surname, $email);
        }
        */
       //只要存在类文件的,这里就可以自动适配.用指定类来初始化实例.如工厂模具一样造出来
       $classname = __NAMESPACE__ . '\\' . ucfirst($type);
       if (!class_exists($classname)) {
           throw new Exception('Wrong type.');
       }
       return new $classname($id, $firstname, $surname, $email);
    }
}

?>

Config.php

<?php

namespace Bookstore\Utils;

use Bookstore\Exceptions\NotFoundException;

require_once __DIR__ . '/NotFoundException.php';

class Config {
    private $data;
    //类静态变量,保证变量唯一性
    private static $instance;
    
    //构造函数私有化,类外部不可以调用.
    private function __construct() {
        $json = file_get_contents(__DIR__ . '/app.json');
        $this->data = json_decode($json, true);
    }
    
    //单例模式,保证只实例化一个类.
    public static function getInstance() {
        if (self::$instance == null) {
            //是可以自己实例化自己的.
            self::$instance = new Config();
        }
        return self::$instance;
    }
    
    public function get($key) {
        if (!isset($this->data[$key])) {
            throw new NotFoundException("Key $key not in config.");
        }
        return $this->data[$key];
    }
}
?>

app.json

{
    "db": {
        "user": "Luke",
        "password": "Skywalker"
    }
}

test.php

<?php
//使用命名空间,易于在大型应用中管理和组织php类.
use Bookstor\Domain\Book;
use Bookstore\Domain\Customer;
use Bookstore\Domain\CustomerFactory;
use Bookstore\Domain\Person;
use Bookstore\Domain\Basic;
use Bookstore\Domain\Premium;
use Bookstore\Utils\Unique;
use Bookstore\Utils\Config;
use Bookstore\Exceptions\InvalidIdException;
use Bookstore\Exceptions\ExceedeMaxAllowedException;

//命名空间可以直接use,但如果这个命名空间没有在标准约定位置,且没有自动载入的话,需要使用require来手工定位一下.
require_once __DIR__ . '/Unique.php';
require_once __DIR__ . '/Config.php';
require_once __DIR__ . '/Book.php';
require_once __DIR__ . '/Customer.php';
require_once __DIR__ . '/CustomerFactory.php';
require_once __DIR__ . '/Person.php';
require_once __DIR__ . '/Basic.php';
require_once __DIR__ . '/Premium.php';
require_once __DIR__ . '/InvalidIdException.php';
require_once __DIR__ . '/ExceedeMaxAllowedException.php';

$basic = CustomerFactory::factory('basic', 2, 'mary', 'poppins', 'mary@poppins.com');
echo $basic->getId(). '<br/>';

$config = Config::getInstance();
$dbConfig = $config->get('db');
var_dump($dbConfig);

    
?>

浏览器输出:

2
array(2) { ["user"]=> string(4) "Luke" ["password"]=> string(9) "Skywalker" }

 

转载于:https://www.cnblogs.com/aguncn/p/11131412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值