search
HomeBackend DevelopmentPHP TutorialComparison of PHP simple factory pattern, factory method pattern and abstract factory pattern

PHP Factory PatternConcept: Factory pattern is a class that has certain methods that create objects for you. You can use a factory class to create objects without using new directly. This way, if you want to change the type of object created, you only need to change the factory. All code using this factory is automatically changed.
According to different levels of abstraction, PHP factory patterns are divided into: simple factory pattern, factory method pattern and abstract factory pattern

Simple factory pattern:

/**
 *简单工厂模式与工厂方法模式比较。
 *简单工厂又叫静态工厂方法模式,这样理解可以确定,简单工厂模式是通过一个静态方法创建对象的。 
 */
interface  people {
    function  jiehun();
}
class man implements people{
    function jiehun() {
        echo &#39;送玫瑰,送戒指!<br>&#39;;
    }
}
 
class women implements people {
    function jiehun() {
        echo &#39;穿婚纱!<br>&#39;;
    }
}
 
class SimpleFactoty {
    // 简单工厂里的静态方法
    static function createMan() {
        return new     man;
    }
    static function createWomen() {
        return new     women;
    }
    
}
 
$man = SimpleFactoty::createMan();
$man->jiehun();
$man = SimpleFactoty::createWomen();
$man->jiehun();

Factory method pattern:

<?php
/*
 *工厂方法模式:
 *定义一个创建对象的接口,让子类决定哪个类实例化。 他可以解决简单工厂模式中的封闭开放原则问题。<www.phpddt.com整理>
 */
interface  people {
    function  jiehun();
}
class man implements people{
    function jiehun() {
        echo &#39;送玫瑰,送戒指!<br>&#39;;
    }
}
 
class women implements people {
    function jiehun() {
        echo &#39;穿婚纱!<br>&#39;;
    }
}
 
interface  createMan {  // 注意了,这里是简单工厂本质区别所在,将对象的创建抽象成一个接口。
    function create();
 
}
class FactoryMan implements createMan{
    function create() {
        return  new man;
    }
}
class FactoryWomen implements createMan {
    function create() {
        return new women;
    }
}
 
class  Client {
    // 简单工厂里的静态方法
    function test() {
        $Factory =  new  FactoryMan;
        $man = $Factory->create();
        $man->jiehun();
        
        $Factory =  new  FactoryWomen;
        $man = $Factory->create();
        $man->jiehun();
    }
}
 
$f = new Client;
$f->test();

Abstract factory pattern:

<?php
/*
抽象工厂:提供一个创建一系列相关或相互依赖对象的接口。 
注意:这里和工厂方法的区别是:一系列,而工厂方法则是一个。
那么,我们是否就可以想到在接口create里再增加创建“一系列”对象的方法呢?
*/
interface  people {
    function  jiehun();
}
class Oman implements people{
    function jiehun() {
        echo &#39;美女,我送你玫瑰和戒指!<br>&#39;;
    }
}
class Iman implements people{
    function jiehun() {
        echo &#39;我偷偷喜欢你<br>&#39;;
    }
}
 
class Owomen implements people {
    function jiehun() {
        echo &#39;我要穿婚纱!<br>&#39;;
    }
}
 
class Iwomen implements people {
    function jiehun() {
        echo &#39;我好害羞哦!!<br>&#39;;
    }
}
 
interface  createMan {  // 注意了,这里是本质区别所在,将对象的创建抽象成一个接口。
    function createOpen(); //分为 内敛的和外向的
    function createIntro(); //内向
 
}
class FactoryMan implements createMan{
    function createOpen() {
        return  new  Oman;
    }
    function createIntro() {
        return  new Iman;
    }
}
class FactoryWomen implements createMan {
    function createOpen() {
        return  new  Owomen;
    }
    function createIntro() {
        return  new Iwomen;
    }
}
 
class  Client {
    // 简单工厂里的静态方法
    function test() {
        $Factory =  new  FactoryMan;
        $man = $Factory->createOpen();
        $man->jiehun();
        
        $man = $Factory->createIntro();
        $man->jiehun();
        
        
        $Factory =  new  FactoryWomen;
        $man = $Factory->createOpen();
        $man->jiehun();
        
        $man = $Factory->createIntro();
        $man->jiehun();
        
    }
}
 
$f = new Client;
$f->test();

Difference:

Simple factory mode: used to produce any product in the same hierarchical structure. There is nothing you can do about adding new products

Factory mode: used to produce fixed products in the same hierarchical structure. (Supports adding any product)
Abstract factory: used to produce all products of different product families. (There is nothing you can do about adding new products; adding product families is supported)

The above three factory methods have different levels of support in the two directions of hierarchical structure and product family. So consider which method should be used according to the situation

Scope of application:

Simple factory pattern:

The factory class is responsible for creating fewer objects. The customer only knows the parameters passed into the factory class and does not care about how to create the object.

Factory Method Pattern:

When a class does not know the class of the object it must create or when a class wants a subclass to specify the object it creates, when the class delegates the responsibility of creating the object to multiple helper subclasses You can use the factory method pattern when you have one of these and you want to localize the information about which helper subclass is the delegate.

Abstract Factory Pattern:

A system should not depend on the details of how product class instances are created, composed and expressed. This is important for all forms of factory patterns. This system has more than one product family, and the system only consumes one of the product families. Products belonging to the same product family are used together, and this constraint must be reflected in the system design. The system provides a product class library, and all products appear with the same interface, so that the client does not depend on the implementation.

Whether it is a simple factory pattern, a factory pattern or an abstract factory pattern, they essentially extract the immutable parts and leave the variable parts as interfaces to achieve maximum reuse. Which design pattern is more suitable depends on specific business needs.

For more articles on the comparison of PHP simple factory pattern, factory method pattern and abstract factory pattern, please pay attention to the PHP Chinese website!

Related articles:

Detailed explanation of the specific code to implement the abstract factory pattern in Java

Abstract Factory Pattern of JAVA design pattern

PHP object-oriented development - Abstract Factory Pattern

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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools