search
HomeBackend DevelopmentPHP TutorialPHP简单工厂模式、工厂方法模式和抽象工厂模式比较

PHP工厂模式概念:工厂模式是一种类,它具有为您创建对象的某些方法。您可以使用工厂类创建对象,而不直接使用 new。这样,如果您想要更改所创建的对象类型,只需更改该工厂即可。使用该工厂的所有代码会自动更改。


根据抽象程度不同,PHP工厂模式分为:简单工厂模式、工厂方法模式和抽象工厂模式

简单工厂模式:

/******代码在原文还是git上都有osgit地址   *******/

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


工厂方法模式:


<?php/* *工厂方法模式: *定义一个创建对象的接口,让子类决定哪个类实例化。 他可以解决简单工厂模式中的封闭开放原则问题。<www.phpddt.com整理> */interface  people {function  jiehun();}class man implements people{function jiehun() {        echo '送玫瑰,送戒指!<br>';}} class women implements people {function jiehun() {        echo '穿婚纱!<br>';}} 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();


抽象工厂模式: 


<?php/*抽象工厂:提供一个创建一系列相关或相互依赖对象的接口。 注意:这里和工厂方法的区别是:一系列,而工厂方法则是一个。那么,我们是否就可以想到在接口create里再增加创建“一系列”对象的方法呢?*/interface  people {function  jiehun();}class Oman implements people{function jiehun() {        echo '美女,我送你玫瑰和戒指!<br>';}}class Iman implements people{function jiehun() {        echo '我偷偷喜欢你<br>';}} class Owomen implements people {function jiehun() {        echo '我要穿婚纱!<br>';}} class Iwomen implements people {function jiehun() {        echo '我好害羞哦!!<br>';}} 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();


区别:

简单工厂模式:用来生产同一等级结构中的任意产品。对与增加新的产品,无能为力

工厂模式 :用来生产同一等级结构中的固定产品。(支持增加任意产品)   
抽象工厂 :用来生产不同产品族的全部产品。(对于增加新的产品,无能为力;支持增加产品族)  

以上三种工厂 方法在等级结构和产品族这两个方向上的支持程度不同。所以要根据情况考虑应该使用哪种方法

适用范围:

简单工厂模式:

工厂类负责创建的对象较少,客户只知道传入工厂类的参数,对于如何创建对象不关心。

工厂方法模式:

当一个类不知道它所必须创建对象的类或一个类希望由子类来指定它所创建的对象时,当类将创建对象的职责委托给多个帮助子类中得某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候,可以使用工厂方法模式。

抽象工厂模式:

一个系统不应当依赖于产品类实例何如被创建,组合和表达的细节,这对于所有形态的工厂模式都是重要的。这个系统有多于一个的产品族,而系统只消费其 中某一产品族。同属于同一个产品族的产品是在一起使用的,这一约束必须在系统的设计中体现出来。系统提供一个产品类的库,所有的产品以同样的接口出现,从 而使客户端不依赖于实现。

无论是简单工厂模式、工厂模式还是抽象工厂模式,它们本质上都是将不变的部分提取出来,将可变的部分留作接口,以达到最大程度上的复用。究竟用哪种设计模式更适合,这要根据具体的业务需求来决定。


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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!