PHP面向对象深入研究之【对象生成】

简介:

对象

看个例子

<?php
abstract class Employee { // 雇员
    protected $name;
    function __construct( $name ) {
        $this->name = $name;
    }
    abstract function fire();
}

class Minion extends Employee { // 奴隶 继承 雇员
    function fire() {
        print "{$this->name}: I'll clear my desk\n";
    }
}

class NastyBoss { // 坏老板
    private $employees = array();

    function addEmployee( $employeeName ) { // 添加员工
        $this->employees[] = new Minion( $employeeName ); // 代码灵活性受到限制
    }

    function projectFails() {
        if ( count( $this->employees ) > 0 ) {
            $emp = array_pop( $this->employees );
            $emp->fire(); // 炒鱿鱼
        }
    }
}

$boss = new NastyBoss();
$boss->addEmployee( "harry" );
$boss->addEmployee( "bob" );
$boss->addEmployee( "mary" );
$boss->projectFails();

// output:
// mary: I'll clear my desk
?>

再看一个更具有灵活性的案例

<?php

abstract class Employee {
    protected $name;
    function __construct( $name ) {
        $this->name = $name;
    }
    abstract function fire();
}

class Minion extends Employee {
    function fire() {
        print "{$this->name}: I'll clear my desk\n";
    }
}

class NastyBoss {
    private $employees = array(); 

    function addEmployee( Employee $employee ) { // 传入对象
        $this->employees[] = $employee;
    }

    function projectFails() {
        if ( count( $this->employees ) ) {
            $emp = array_pop( $this->employees );
            $emp->fire();
        }
    }
}

// new Employee class...
class CluedUp extends Employee {
    function fire() {
        print "{$this->name}: I'll call my lawyer\n";
    }
}

$boss = new NastyBoss();
$boss->addEmployee( new Minion( "harry" ) ); // 直接以对象作为参数,更具有灵活性
$boss->addEmployee( new CluedUp( "bob" ) );
$boss->addEmployee( new Minion( "mary" ) );
$boss->projectFails();
$boss->projectFails();
$boss->projectFails();
// output:
// mary: I'll clear my desk
// bob: I'll call my lawyer
// harry: I'll clear my desk
?>

单例

<?php

class Preferences {
    private $props = array();
    private static $instance; // 私有的,静态属性

    private function __construct() { } // 无法实例化,私有的构造函数

    public static function getInstance() { // 返回对象 静态方法才可以被类访问,静态方法中要有静态属性
        if ( empty( self::$instance ) ) {
            self::$instance = new Preferences();
        }
        return self::$instance;
    }

    public function setProperty( $key, $val ) {
        $this->props[$key] = $val;
    }

    public function getProperty( $key ) {
        return $this->props[$key];
    }
}


$pref = Preferences::getInstance();
$pref->setProperty( "name", "matt" );

unset( $pref ); // remove the reference

$pref2 = Preferences::getInstance();
print $pref2->getProperty( "name" ) ."\n"; // demonstrate value is not lost
?>

点评:不能随意创建对象,只能通过Preferences::getInstance()来创建对象。

工厂模式

<?php

abstract class ApptEncoder {
    abstract function encode();
}

class BloggsApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in BloggsCal format\n";
    }
}

class MegaApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in MegaCal format\n";
    }
}

class CommsManager { // 负责生产Bloggs对象
    function getApptEncoder() {
        return new BloggsApptEncoder();
    }
}

$obj = new CommsManager();
$bloggs = $obj->getApptEncoder(); // 获取对象
print $bloggs->encode();
?>
output:
Appointment data encoded in BloggsCal format

进一步增加灵活性设置

<?php

abstract class ApptEncoder {
    abstract function encode();
}

class BloggsApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in BloggsCal format\n";
    }
}

class MegaApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in MegaCal format\n";
    }
}

class CommsManager {
    const BLOGGS = 1;
    const MEGA = 2;
    private $mode ;

    function __construct( $mode ) {
        $this->mode = $mode;
    }

    function getHeaderText() {
        switch ( $this->mode ) {
            case ( self::MEGA ):
                return "MegaCal header\n";
            default:
                return "BloggsCal header\n";
        }
    }
    function getApptEncoder() {
        switch ( $this->mode ) {
            case ( self::MEGA ):
                return new MegaApptEncoder();
            default:
                return new BloggsApptEncoder();
        }
    }
}

$man = new CommsManager( CommsManager::MEGA );
print ( get_class( $man->getApptEncoder() ) )."\n";
$man = new CommsManager( CommsManager::BLOGGS );
print ( get_class( $man->getApptEncoder() ) )."\n";
?>
output:
MegaApptEncoder
BloggsApptEncoder

工厂方法模式要把创建者类与要生产的产品类分离开来。

抽象工厂

通过抽象来来约束,成为一定的规矩。

<?php
abstract class ApptEncoder {
    abstract function encode();
}

class BloggsApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in BloggsCal format\n";
    }
}

class MegaApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in MegaCal format\n";
    }
}


abstract class CommsManager { // 预约
    abstract function getHeaderText();
    abstract function getApptEncoder();
    abstract function getTtdEncoder();
    abstract function getContactEncoder();
    abstract function getFooterText();
}

class BloggsCommsManager extends CommsManager {
    function getHeaderText() {
        return "BloggsCal header\n";
    }

    function getApptEncoder() {
        return new BloggsApptEncoder();
    }

    function getTtdEncoder() {
        return new BloggsTtdEncoder();
    }

    function getContactEncoder() {
        return new BloggsContactEncoder();
    }

    function getFooterText() {
        return "BloggsCal footer\n";
    }
}

class MegaCommsManager extends CommsManager {
    function getHeaderText() {
        return "MegaCal header\n";
    }

    function getApptEncoder() {
        return new MegaApptEncoder();
    }

    function getTtdEncoder() {
        return new MegaTtdEncoder();
    }

    function getContactEncoder() {
        return new MegaContactEncoder();
    }

    function getFooterText() {
        return "MegaCal footer\n";
    }
}


$mgr = new MegaCommsManager();
print $mgr->getHeaderText();
print $mgr->getApptEncoder()->encode(); // 对象调用方法,返回对象,继续调用方法。
print $mgr->getFooterText();

?>
output:
MegaCal header
Appointment data encoded in MegaCal format
MegaCal footer

更加牛逼的实现

<?php
// 根据类图,规划类的代码。从大局入手。
abstract class ApptEncoder {
    abstract function encode();
}

class BloggsApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in BloggsCal format\n";
    }
}

class MegaApptEncoder extends ApptEncoder {
    function encode() {
        return "Appointment data encoded in MegaCal format\n";
    }
}

abstract class CommsManager {
    const APPT    = 1;
    const TTD     = 2;
    const CONTACT = 3;
    abstract function getHeaderText();
    abstract function make( $flag_int ); // int标记
    abstract function getFooterText();
}

class BloggsCommsManager extends CommsManager {
    function getHeaderText() {
        return "BloggsCal header\n";
    }
    function make( $flag_int ) {
        switch ( $flag_int ) {
            case self::APPT: // self直接控制常量
                return new BloggsApptEncoder();
            case self::CONTACT:
                return new BloggsContactEncoder();
            case self::TTD:
                return new BloggsTtdEncoder();
        }
    }

    function getFooterText() {
        return "BloggsCal footer\n";
    }
}

$mgr = new BloggsCommsManager();
print $mgr->getHeaderText();
print $mgr->make( CommsManager::APPT )->encode();
print $mgr->getFooterText();


?>
output:
BloggsCal header
Appointment data encoded in BloggsCal format
BloggsCal footer

原型模式

改造成一个保存具体产品的工厂类。

<?php

class Sea {} // 大海
class EarthSea extends Sea {}
class MarsSea extends Sea {}

class Plains {} // 平原
class EarthPlains extends Plains {}
class MarsPlains extends Plains {}

class Forest {} // 森林
class EarthForest extends Forest {}
class MarsForest extends Forest {}

class TerrainFactory { // 地域工厂
    private $sea;
    private $forest;
    private $plains;

    function __construct( Sea $sea, Plains $plains, Forest $forest ) { // 定义变量为类对象
        $this->sea = $sea;
        $this->plains = $plains;
        $this->forest = $forest;
    }

    function getSea( ) {
        return clone $this->sea; // 克隆
    }

    function getPlains( ) {
        return clone $this->plains;
    }

    function getForest( ) {
        return clone $this->forest;
    }
}

$factory = new TerrainFactory( new EarthSea(),
    new EarthPlains(),
    new EarthForest() );
print_r( $factory->getSea() );
print_r( $factory->getPlains() );
print_r( $factory->getForest() );
?>
output:
EarthSea Object
(
)
EarthPlains Object
(
)
EarthForest Object
(
)
相关文章
|
17天前
|
存储 监控 算法
基于 PHP 布隆过滤器的局域网监控管理工具异常行为检测算法研究
布隆过滤器以其高效的空间利用率和毫秒级查询性能,为局域网监控管理工具提供轻量化异常设备检测方案。相比传统数据库,显著降低延迟与资源消耗,适配边缘设备部署需求,提升网络安全实时防护能力。(238字)
104 0
|
7月前
|
监控 算法 安全
基于 PHP 语言深度优先搜索算法的局域网网络监控软件研究
在当下数字化时代,局域网作为企业与机构内部信息交互的核心载体,其稳定性与安全性备受关注。局域网网络监控软件随之兴起,成为保障网络正常运转的关键工具。此类软件的高效运行依托于多种数据结构与算法,本文将聚焦深度优先搜索(DFS)算法,探究其在局域网网络监控软件中的应用,并借助 PHP 语言代码示例予以详细阐释。
133 1
|
5月前
|
监控 算法 安全
基于 PHP 的员工电脑桌面监控软件中图像差分算法的设计与实现研究
本文探讨了一种基于PHP语言开发的图像差分算法,用于员工计算机操作行为监控系统。算法通过分块比较策略和动态阈值机制,高效检测屏幕画面变化,显著降低计算复杂度与内存占用。实验表明,相比传统像素级差分算法,该方法将处理时间缩短88%,峰值内存使用量减少70%。文章还介绍了算法在工作效率优化、信息安全防护等方面的应用价值,并分析了数据隐私保护、算法准确性及资源消耗等挑战。未来可通过融合深度学习等技术进一步提升系统智能化水平。
83 2
|
缓存 安全 PHP
PHP中的魔术方法与对象序列化
本文将深入探讨PHP中的魔术方法,特别是与对象序列化和反序列化相关的__sleep()和__wakeup()方法。通过实例解析,帮助读者理解如何在实际应用中有效利用这些魔术方法,提高开发效率和代码质量。
|
7月前
|
存储 监控 算法
基于 PHP 语言的滑动窗口频率统计算法在公司局域网监控电脑日志分析中的应用研究
在当代企业网络架构中,公司局域网监控电脑系统需实时处理海量终端设备产生的连接日志。每台设备平均每分钟生成 3 至 5 条网络请求记录,这对监控系统的数据处理能力提出了极高要求。传统关系型数据库在应对这种高频写入场景时,性能往往难以令人满意。故而,引入特定的内存数据结构与优化算法成为必然选择。
177 3
|
11月前
|
存储 PHP
09 PHP高级面向对象,大多数人不了解的东西!
路老师分享了PHP语言的高级应用,包括final关键字、抽象类、接口使用、对象类型检测及魔术方法等。通过实例详细讲解了PHP面向对象编程的核心概念和技术要点,帮助读者深入理解和掌握PHP。
86 3
|
11月前
|
Java PHP 开发者
08 PHP面向对象的高级操作
路老师分享PHP语言知识,帮助大家入门并深入了解PHP。内容涵盖构造方法、析构方法、继承、多态、`$this-&gt;`与`::`操作符的使用,以及数据隐藏等核心概念。通过详细示例,讲解如何在实际开发中运用这些技术。适合初学者和进阶开发者学习。
95 2
|
11月前
|
PHP
07 PHP的面向对象你真的了解吗?
路老师分享PHP语言知识,帮助大家入门并深入了解PHP。本文介绍了面向对象编程的基础概念,包括类、对象、封装性、继承性和多态性,以及类的定义、方法、实例化和成员变量等内容。下篇将讲解构造函数、析构函数及PHP对象的高级应用。
110 2
|
Java PHP 数据安全/隐私保护
PHP 面向对象,构造函数,析构函数,继承,方法的重写,接口抽象类,static,final,this,parent,self的异同和作用
本文详细介绍了PHP面向对象编程的一系列核心概念和用法,包括构造函数、析构函数、继承、方法重写、访问控制、接口、抽象类、静态成员、final关键字、以及this、self、parent这三个关键字的异同和作用。通过具体示例代码,展示了如何在PHP中使用这些面向对象的特性,以及它们在实际开发中的应用。
PHP 面向对象,构造函数,析构函数,继承,方法的重写,接口抽象类,static,final,this,parent,self的异同和作用