search
HomeBackend DevelopmentPHP TutorialPHP五种常用的设计模式--工厂模式

一直对设计模式有一种敬畏之心,每次想要看设计模式的时候就会想到Erich Gamma,Richard Helm , Ralph Johnson, John Vlissides的黑皮《设计模式》,基本都望而止步,要把那本书看完可不是一时半会的,而且在没有项目经验的情况下,个人感觉基本都是纸上谈兵。

今天在IBM Developerworks上看到一篇文章将PHP中常用的五种设计模式,感觉还不错,而且只有五种五种五种(重要的强调三遍)!先从简单的入手,把这五种消灭了再说。以后慢慢学习其他的设计模式。

工厂模式(Factory Pattern)

工厂这个词的使用是非常形象,字面意思可以这样认为,这种模式下,我们有一个工厂,这个工厂生产很多一种或者几种产品(其实多种的情况是覆盖了一种的),但是每个产品怎么生产和包装的我们不知道,其实我们也不需要知道,知道的越多你就越迷糊,以后你的行为就受制于太多杂事,也就是我们常说的耦合度太高,因此我们就将所有的事情交给工厂负责,我们只用告诉工厂需要什么,工厂把产品交付给你就是了。一旦产品的工艺发生改变,工厂负责就好,你使用该产品的工艺不受影响。因此工厂模式可以大大的降低系统的耦合度,增强系统的稳定性,当然也会提高代码的复用率。

在实际的程序设计中,工厂相当于一个对外的接口,那么这个接口的返回类型是确定的,那么我们怎么通过这个工厂来生产不同的产品发回给客户呢?很简单,做一个所有产品的“模子”就可以,这个“模子”有每个产品的所有特征,但是不能用,需要具体的产品实现这些特性,就是我们常说的Interface。
使用类图表示如下:

PHP的实现
  • 编写一个接口 Product.php
  • <?php/** * Created by PhpStorm. * User: Defei * Date: 2015/8/8 * Time: 16:14 */interface Product{    public function getName();}
  • 设计一个产品A实现Product接口
  • <?php /** * Created by PhpStorm. * User: Defei * Date: 2015/8/8 * Time: 16:16 */ class ProductA implements Product{ public function getName(){ // TODO: Implement getName() method. echo '我是产品A'; } }
  • 设计产品B实现Product接口
  • <?php /** * Created by PhpStorm. * User: Defei * Date: 2015/8/8 * Time: 16:17 */ class ProductB implements Product{ public function getName(){ // TODO: Implement getName() method. echo '我是产品B'; } }
  • 建造一座工厂生产产品A和B
  • <?php/** * Created by PhpStorm. * User: Defei * Date: 2015/8/8 * Time: 16:18 */class ProductFactory{    /** * @param $product_name * @return mixed */    public function factory($product_name){        return new $product_name; //PHP可以使用名字直接new一个同名的对象这个很方便    }}
    测试

    产品A和B已经设计好了,工厂也建好了,下一步就是测试一下这个工厂对的生产能力如何。

    <?php /** * Created by PhpStorm. * User: Defei * Date: 2015/8/8 * Time: 16:20 */ include 'ProductFactory.php'; include 'Product.php'; include 'ProductA.php'; include 'ProductB.php'; $factory = new ProductFactory(); echo $factory->factory('ProductA')->getName().PHP_EOL; echo $factory->factory('ProductB')->getName(); 

    输出结果如下:

    版权声明:本文为博主原创文章,未经博主允许不得转载。

    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
    Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

    Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

    cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

    The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

    Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

    Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

    12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

    Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

    Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

    The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

    Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

    Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

    PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

    PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

    How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

    Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft