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

在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" }

php中的设计模式---工厂模式及单例模式的更多相关文章

  1. [Head First设计模式]饺子馆(冬至)中的设计模式——工厂模式

    系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...

  2. PHP设计模式-工厂模式、单例模式、注册模式

    本文参考慕课网<大话PHP设计模式>-第五章内容编写,视频路径为:http://www.imooc.com/video/4876 推荐阅读我之前的文章:php的设计模式 三种基本设计模式, ...

  3. php设计模式 工厂模式和单例模式

    一.单例模式//让该类在外界无法造对象//让外界可以造一个对象,做一个静态方法返回对象//在类里面通过让静态变量控制返回对象只能是一个. 单例模式的要点有三个: 一是某个类只能有一个实例: 二是它必须 ...

  4. [Head First设计模式]抢票中的设计模式——代理模式

    系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...

  5. [Head First设计模式]餐馆中的设计模式——命令模式

    系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...

  6. 在商城系统中使用设计模式----简单工厂模式之在springboot中使用简单工厂模式

    1.前言: 不了解简单工厂模式请先移步:在商城中使用简单工厂.在这里主要是对springboot中使用简单工厂模式进行解析. 2.问题: 什么是简单工厂:它的实现方式是由一个工厂类根据传入的参数,动态 ...

  7. .NET设计模式: 工厂模式

    .NET设计模式: 工厂模式(转) 转自:http://www.cnblogs.com/bit-sand/archive/2008/01/25/1053207.html   .NET设计模式(1): ...

  8. Spring中如何使用工厂模式实现程序解耦?

    目录 1. 啥是耦合.解耦? 2. jdbc程序进行解耦 3.传统dao.service.controller的程序耦合性 4.使用工厂模式实现解耦 5.工厂模式改进 6.结语 @ 1. 啥是耦合.解 ...

  9. 【设计模式】Java设计模式 -工厂模式

    [设计模式]Java设计模式 -工厂模式 不断学习才是王道 继续踏上学习之路,学之分享笔记 总有一天我也能像各位大佬一样 一个有梦有戏的人 @怒放吧德德 分享学习心得,欢迎指正,大家一起学习成长! 目 ...

随机推荐

  1. Spring Cloud @RefreshScope 原理是什么?

    要清楚RefreshScope,先要了解Scope Scope(org.springframework.beans.factory.config.Scope)是Spring 2.0开始就有的核心的概念 ...

  2. 一张MGR切换的图,不解释

  3. 《Linux就该这么学》培训笔记_ch19_使用PXE+Kickstart无人值守安装服务

    <Linux就该这么学>培训笔记_ch19_使用PXE+Kickstart无人值守安装服务 文章最后会post上书本的笔记照片. 文章主要内容: 无人值守系统 部署相关服务程序 配置DHC ...

  4. maven 依赖优化

    1.mvn dependency:list  列出项目用到的依赖 2.查看依赖树 mvn dependency:tree 3.mvn dependency:analyze Used undeclare ...

  5. linux 操作文件夹

    创建文件夹[mkdir] 一.mkdir命令使用权限 所有用户都可以在终端使用 mkdir 命令在拥有权限的文件夹创建文件夹或目录. 二.mkdir命令使用格式 格式:mkdir [选项] DirNa ...

  6. laravel 可以做什么

    laravel 可以做什么? Laravel是一套简洁.优雅的PHP Web开发框架(PHP Web Framework).它可以让你从面条一样杂乱的代码中解脱出来:它可以帮你构建一个完美的网络APP ...

  7. 备忘录(Memento)模式

    备忘录模式又叫做快照模式或者Token模式. 备忘录对象是一个用来存储另一个对象内部状态的快照的对象.备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捕捉住,并外部化,存储起来,从而可以在将来 ...

  8. 使用springboot mybatis 查询时实体类中的驼峰字段值为null

    看到返回结果以后主要分析了一下情况: 实体类的get.set方法确实 mapper.xml文件中的resultMap.resultType等原因导致 数据库中数据存在问题 经过检查与验证发现以上都不存 ...

  9. ZYNQ笔记(5):软中断实现核间通信

    ZYNQ包括一个 FPGA 和两个 ARM,多个 ARM 核心相对独立的运行不同的任务,每个核心可能运行不同的操作系统或裸机程序,但是有一个主要核心,用来控制整个系统以及其他从核心的允许.因此我们可以 ...

  10. python第五章程序练习题

    5.2 def isOdd(a): if a%2!=0: return True else: a=eval(input()) print(isOdd(a)) 5.3 def isNum(x): try ...