博客列表 >php设计模式-2018年-5月11日01:02

php设计模式-2018年-5月11日01:02

植树青年小江同志的博客
植树青年小江同志的博客原创
2018年05月11日 01:03:26650浏览

单例模式

实例

<?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'));

运行实例 »

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


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议