PHP设计模式之工厂模式学习笔记
本文章来给大家介绍php5中的一个新东西,就是工厂模式了,这里是我常用工厂模式的一些学习笔记,下面与大家一同分享有需要了解的朋友可参考.
在大型系统中,许多代码依赖于少数几个关键类.需要更改这些类时,可能会出现困难.例如,假设您有一个从文件读取的 User 类.您希望将其更改为从数据库读取的其他类,但是,所有的代码都引用从文件读取的原始类.这时候,使用工厂模式会很方便.工厂模式是一种类,它具有为您创建对象的某些方法.您可以使用工厂类创建对象,而不直接使用 new.这样,如果您想要更改所创建的对象类型,只需更改该工厂即可.使用该工厂的所有代码会自动更改.
示例1:显示工厂类的一个示列.
等式的服务器端包括两个部分:数据库和一组 PHP 页面,这些页面允许您添加反馈、请求反馈列表并获取与特定反馈相关的文章
实例代码如下:
<?php interface IUser { function getName(); } class User implements IUser { public function __construct($id) { } public function getName() { return "Jack"; } } class UserFactory { public static function Create($id) { return new User($id); } } $uo = UserFactory::Create(1); echo ($uo->getName() . "n"); ?>
IUser接口定义用户对象应执行什么操作.IUser 的实现称为 User,UserFactory 工厂类则创建 IUser 对象.此关系可以用图1中的UML表示.
图 1. 工厂类及其相关 IUser 接口和用户类如果您使用 php 解释器在命令行上运行此代码,将得到如下结果:
% php factory1.php Jack %
测试代码会向工厂请求 User 对象,并输出 getName 方法的结果.有一种工厂模式的变体使用工厂方法.类中的这些公共静态方法构造该类型的对象.如果创建此类型的对象非常重要,此方法非常有用.例如,假设您需要先创建对 象,然后设置许多属性.此版本的工厂模式会将该进程封装在单个位置中,这样,不用复制复杂的初始化代码,也不必将复制好的代码在在代码库中到处粘贴.
示例2 显示使用工厂方法的一个示例.
实例代码如下:
<?php interface IUser { function getName(); } class User implements IUser { public static function Load($id) { return new User($id); } public static function Create() { return new User(null); } public function __construct($id) { } public function getName() { return "Jack"; } } $uo = User::Load(1); echo ($uo->getName() . "n"); ?>
好了上面讲了很多了, 下面我来来看个实例
我们建立以下四个文件
index.php实例代码如下:
<?php include_once ("f.inc.php"); $f = new factory; $t1 = & $f->create('T1'); echo $t1->getName(); echo $config; ?>
f.inc.php实例代码如下:
<?php class factory { function factory() { $this->mClasses = array( 'T1' => 't1.inc.php', 'T2' => 't2.inc.php' ); } function &create($class) { if (!class_exists($class)) { require_once ($this->mClasses[$class]); } return new $class; } } ?>
t1.inc.php实例代码如下:
<?php global $config; $config = 'surfchen'; class T1 { var $mName = 'name::T1'; function getName() { return $this->mName; } } ?>
t2.inc.php实例代码如下:
<?php class T2 { function T2() { echo 't2 is ok'; } } ?>
在index.php里,我们通过一个factory类来创建其他的类实例.在factory里,保存有一个数组$this->mClasses,格式为array(“类名”=>”类文件路径”).我们通过factory::create()来创建一个类实例的时候,在create()里,会首先检测类是否存在,如果不存在,就根据$this->mClasses把类对应的类文件包含进来.然后创建并返回一个该类的实例.这样,我们只需要把factory类文件包含进执行的脚本(如index.php)中就可以了.大家可能还注意到了在t1.inc.php中的这两行代码.
实例代码如下:
global $config; $config='surfchen';
为什么需要global呢?因为t1.inc.php是在factory::create中被包含的,t1文件中的变量将会默认为create的函数级变量.所以我们需要对其中的变量(如$config)进行global以便index.php能访问到.运行index.php,将会输出
实例代码如下:
name::T1surfchen
教程链接:
随意转载~但请保留教程地址★

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

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.

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).

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.

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.

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 advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

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.
