Blogger Information
Blog 28
fans 0
comment 0
visits 16656
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php设计模式-2018年-5月11日01:02
植树青年小江同志的博客
Original
662 people have browsed it

单例模式

实例

<?php
namespace Singleton\index;

/**
* 单例模式 
*/


class Singleton
{
  private static $instance = null;



  private function __construct()
  {

  }

  public static function getInstance()
  {
    if (is_null(self::$instance)){
      self:$instance = new self();
    } 

    return self::$instance;
  }

  // 防止被克隆

  private function __clone()
  {
    
  }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

工厂模式

实例

<?php

namespace Factory\index;

class Honda
{
  private $name;

  private $power;

  public function __construct($name, $power)
  {
    $this->name = $name;
    $this->power = $power;
  }

  public function getNameAndPower()
  {
    return $this->name . '拥有' . $this->power . '马力';
  }
}

class HondaFactory
{
  public static function create($name, $power)
  {
    return new Honda($name, $power);
  }
}


$civic = HondaFactory::create('Civic', '177');

print_r($civic->getNameAndPower());

运行实例 »

点击 "运行实例" 按钮查看在线实例

注册树模式

实例

<?php

namespace Register\index;

class Register
{
  public static $store = array();

  public static function set ($key, $value)
  {
    self::$store[$key] = $value;
  }

  public static function get($key)
  {
    return self::$store[$key];
  }

  public static function unset($key)
  {
    unset(self::$store[$key]);
  }
}

// class Demo1 {}
// class Demo2 {}
// class Demo3 {}

//   Register::set('demo1',new Demo1);
// Register::set('demo2',new Demo2);
// Register::set('demo3',new Demo3);

// //检测是否上树?
// var_dump(Register::$store);
// echo '<hr>';
// echo '<pre>'.print_r(Register::$store,true).'</pre>';

// echo '<hr>';

// //用注册类的get方法查看
// var_dump(Register::get('demo2'));

// //删除对象池中的某个实例对象
// Register::unset('demo2');

// //再次查看demo2对象,已经不能被查看了,因为被销毁了
// var_dump(Register::get('demo2'));

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post