Table of Contents
PHP五种常用的设计模式——工厂模式
工厂模式(Factory Pattern
测试" >测试
Home php教程 php手册 PHP五种常用的设计模式工厂模式

PHP五种常用的设计模式工厂模式

Jun 13, 2016 am 08:56 AM
factory Commonly used Design Patterns

PHP五种常用的设计模式——工厂模式

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

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

工厂模式(Factory Pattern

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

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

PHP的实现
编写一个接口 Product.php
<code class="hljs" java=""><!--?php
/**
* Created by PhpStorm.
* User: Defei
* Date: 2015/8/8
* Time: 16:14
*/

interface Product{
    public function getName();
}</code--></code>
Copy after login
设计一个产品<code>A实现Product接口
<code class="hljs" java=""><code class="hljs" xml=""><!--?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';
    }
}</code--></code></code>
Copy after login
<code class="hljs" xml="">设计产品<code>B实现Product接口
<code class="hljs" java=""><code class="hljs" xml=""><code class="hljs" xml=""><!--?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';
    }

}</code--></code></code></code>
Copy after login
<code class="hljs" xml=""><code class="hljs" xml="">建造一座工厂生产产品<code>AB
<code class="hljs" java=""><code class="hljs" xml=""><code class="hljs" xml=""><code class="hljs" java=""><!--?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一个同名的对象这个很方便
    }

}</code--></code></code></code></code>
Copy after login
<code class="hljs" xml=""><code class="hljs" xml=""><code class="hljs" java="">测试

<code class="hljs" xml=""><code class="hljs" xml=""><code class="hljs" java="">产品<code>AB已经设计好了,工厂也建好了,下一步就是测试一下这个工厂对的生产能力如何。

<code class="hljs" java=""><code class="hljs" xml=""><code class="hljs" xml=""><code class="hljs" java=""><code class="hljs" xml=""><!--?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(&#39;ProductA&#39;)->getName().PHP_EOL;
echo $factory->factory(&#39;ProductB&#39;)->getName();
</code></code></code></code></code>
Copy after login

<code class="hljs" xml=""><code class="hljs" xml=""><code class="hljs" java="">输出结果如下:<br>

 

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

15 commonly used currency circle escape index technology analysis 15 commonly used currency circle escape index technology analysis Mar 03, 2025 pm 05:48 PM

In-depth analysis of the top 15 Bitcoin Escape Index: Market Outlook for 2025 This article deeply analyzes fifteen commonly used Bitcoin Escape Index, among which the Bitcoin Rhodl ratio, USDT current wealth management and altcoin seasonal index have reached the Escape Index in 2024, attracting market attention. How should investors deal with potential risks? Let us interpret these indicators one by one and explore reasonable response strategies. 1. Detailed explanation of key indicators AHR999 coin hoarding indicator: Created by ahr999, assisting Bitcoin fixed investment strategy. The current value is 1.21, which is in the wait-and-see range, so it is recommended to be cautious. Link to AHR999 Escape Top Indicator: A supplement to AHR999 Coin Hoarding Indicator, used to identify the top of the market. The current value is 2.48, this week

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

See all articles