search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the usage of PHP's singleton mode and factory mode

设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
毫无疑问,设计模式于己于他人于系统都是多赢的;设计模式使代码编制真正工程化;设计模式是软件工程的基石脉络,如同大厦的结构一样。
单例模式
当需要保证某个对象只能有一个实例的时候,单例模式非常有用。它把创建对象的控制权委托到一个单一的点上,任何时候应用程序都只会仅有一个实例存在。单例类不应该可以在类的外部进行实例化一个单例类应该具备以下几个要素。
必须拥有一个访问级别为 private 的构造函数,有效防止类被随意实例化。
必须拥有一个保存类的实例的静态变量。
必须拥有一个访问这个实例的公共的静态方法,该方法通常被命名为 GetInstance()。
必须拥有一个私有的空的clone方法,防止实例被克隆复制。
下面用一个简单的单例类的例子来说明

  1. classClassName
    {
    publicstatic $_instance;
    privatefunction construct()
    {
    # code...
    }
    privatefunction clone()
    {
    # empty
    }
    publicstaticfunctionGetInstance()
    {
    if(!(self::$_instance instanceofself))
    {
    self::$_instance =newself();
    }
    returnself::$_instance;
    }
    publicfunctionSayHi()
    {
            echo "Hi boy!";
    }
    }
    $App=ClassName::GetInstance();
    $App->SayHi();
    /**
     *
     * Output
     *
     * Hi boy!
     *
     */

简单工厂模式
当你有大量的实现同一接口的类的时候,在合适的时候实例化合适的类,如果把这些 new 分散到项目的各个角落,不仅会使业务逻辑变的混乱并且使得项目难以维护。这时候如果引进工厂模式的概念,就能很好的处理这个问题。我们还可以通过应用程序配置或者提供参数的形式让工厂类为我们返回合适的的实例。
工厂类,它把实例化类的过程放到各工厂类里头,专门用来创建其他类的对象。工厂模式往往配合接口一起使用,这样应用程序就不必要知道这些被实例化的类的具体细节,只要知道工厂返回的是支持某个接口的类可以很方便的使用了。下面简单举例说明下工厂类的使用。

  1. interfaceProductInterface
    {
    publicfunction showProductInfo();
    }
    classProductAimplementsProductInterface
    {
    function showProductInfo()
    {
            echo 'This is product A.';
    }
    }
    classProductBimplementsProductInterface
    {
    function showProductInfo()
    {
            echo 'This is product B.';
    }
    }
    classProductFactory
    {
    publicstaticfunction factory($ProductType)
    {
            $ProductType ='Product'. strtoupper($ProductType);
    if(class_exists($ProductType))
    {
    returnnew $ProductType();
    }
    else
    {
    thrownewException("Error Processing Request",1);
    }
    }
    }
    //这里需要一个产品型号为 A 的对象
    $x =ProductFactory::factory('A');
    $x -> showProductInfo();
    //这里需要一个产品型号为 B 的对象
    $o =ProductFactory::factory('B');
    $o -> showProductInfo();
    //都可以调用showProductInfo方法,因为都实现了接口 ProductInterface.

小结
模式就像是软件工程的基石脉络像大厦的设计图纸一样,这里接触了两种模式:单例模式和工程模式。单例类中存在一个静态变量保存着自身的一个实例,并且提供了获取这个静态变量的静态方法。单例类还应该把构造函数和clone函数标记为私有的,防止破换实例的唯一性。工厂模式根据传入的参数或程序的配置来创建不同的类型实例,工厂类返回的是对象,工厂类在多态性编程实践中是至关重要的。             

The above is the detailed content of Detailed explanation of the usage of PHP's singleton mode and factory mode. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools