zoukankan      html  css  js  c++  java
  • PHP Patterns (Factory & Singleton)

    Factory

    定义:

    <?php
    class Example
    {
        // The factory method
        public static function factory($type)
        {
            if (include_once 'Drivers/' . $type . '.php') {
                $classname = 'Driver_' . $type;
                return new $classname;
            } else {
                throw new Exception ('Driver not found');
            }
        }
    }
    ?> 

    使用:

    <?php
    // Load a MySQL Driver
    $mysql = Example::factory('MySQL');
    
    // Load a SQLite Driver
    $sqlite = Example::factory('SQLite');
    ?> 

    Singleton

    定义:

    <?php
    class Example
    {
        // Hold an instance of the class
        private static $instance;
        
        // A private constructor; prevents direct creation of object
        private function __construct() 
        {
            echo 'I am constructed';
        }
    
        // The singleton method
        public static function singleton() 
        {
            if (!isset(self::$instance)) {
                $c = __CLASS__;
                self::$instance = new $c;
            }
    
            return self::$instance;
        }
        
        // Example method
        public function bark()
        {
            echo 'Woof!';
        }
    
        // Prevent users to clone the instance
        public function __clone()
        {
            trigger_error('Clone is not allowed.', E_USER_ERROR);
        }
    
    }
    
    ?> 

    使用:

    <?php
    // This would fail because the constructor is private
    $test = new Example;
    
    // This will always retrieve a single instance of the class
    $test = Example::singleton();
    $test->bark();
    
    // This will issue an E_USER_ERROR.
    $test_clone = clone($test);
    
    ?> 
  • 相关阅读:
    Asp.net的安全问题
    周末了
    GDI+ 取得文本的宽度和高度
    Family的解释
    日语:名词并列
    第一次来入住园里
    All About Floats
    smarty的基本配置
    apache:一个ip绑定多个域名的问题
    CSS Overflow属性详解
  • 原文地址:https://www.cnblogs.com/bruceleeliya/p/2736722.html
Copyright © 2011-2022 走看看