search
HomeBackend DevelopmentPHP TutorialPHP经典面试题之设计模式(经常遇到)_php实例

设计模式在面试过程中经常会提到,有时候还会让我们举例说明各种设计模式的应用场景。

使用设计模式可以减轻我们的工作量,优化我们的代码。

设计模式非常的多,这里介绍单例模式,工厂模式,组合模式,策略模式4种模式

如果有代码有什么问题或者有更好的方式请告知,谢谢!!!!!

/**
 * 单例模式
 * @author YangYang <1812271619@qq.com>
 * 可以想成在一次http请求中只产生该类的一个对象(即只new classname一次)
 * 经典的例子是数据库连接(redis,mongodb,memcache等)
 * 在一次http请求中我们可能需要对数据库做增删改查多条sql操作
 * 但是如果一次http请求中每执行一条sql我们就mysql_connect(),很明显会导致服务器资源的浪费
 * 为了节约资源,就可以通过单例模式来实现一次http请求只做一次mysql_connect()
 * 即将mysql_connect()放在类方法的__construct中,并将__construct方法做成私有,
 * 这样只能通过getInstance()方法来获得mysql_connect()的资源连接符
 * getInstance()方法中判断是否已经存在myql连接符,如果存在就直接返回该连接符
 * 否则new classname()即调用了__construct方法执行了mysql_connect()得到了资源连接符,并返回连接符
 * 因为现在PHP已不再建议直接使用mysql函数进行数据库操作,而是建议通过PDO进行数据库操作,所以这里写一个简易PDO连接的单例模式
 * 这里只是讲解单例原理,数据库的防sql注入等问题不做考虑
 * 准备工作 数据库:test 数据表:user 字段:id name 记录:1 CodeAnti
 * 最终运行结果: 数据表user中id=1这条记录被删除
 */
class SinglePDO
{
    private static $_instance = null;
    private $_pdo;
    //私有,防止外部直接实例化new SinglePDO(...)
    private function __construct($dsn,$dbUser,$dbPassword)
    {
        try{
            $this->_pdo = new PDO($dsn,$dbUser,$dbPassword);
            $this->_pdo->exec('set names utf8');
        }catch(PDOException $e){
            die("Error:{$e->getMessage()}");
        }
    }
    //私有,防止克隆
    private function __clone(){}
    //获取连接实例
    public static function getInstance($dsn,$dbUser,$dbPassword)
    {
        if(self::$_instance === null)
            self::$_instance = new self($dsn,$dbUser,$dbPassword);
        return self::$_instance;
    }
    //执行sql
    public function execSql($sql)
    {
        $result = $this->_pdo->exec($sql);
        return $result;
    }
}

$dsn = "mysql:host=localhost;dbname=test";
$dbUser = "root";
$dbPassword = "";
$sql = "delete from user where id = 1";
$pdo = SinglePDO::getInstance($dsn,$dbUser,$dbPassword);
$result = $pdo->execSql($sql); //$pdo->execSql($sql)多次调用,但仍然是同一个pdo对象
print_r($result);

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.