


Understand simple factories, factory methods, and abstract factories in one article
Simple Factory Mode
Basically everyone has a music player in their mobile phone. The currently popular players are: QQ Music, Kugou Music , Sogou Music, NetEase Cloud Music, Tiantian Dongting, etc. The following is a piece of code about playing music:
if ($type == 'QQ') { $player = new QQPlayer(); } else if ($type == 'Wy') { $player = new WyPlayer(); } else if ($type == 'KG') { $player = new KGPlayer(); } else { $palyer = null; } $player->on(); // 打开播放器 $player->choiceMusic('我不配'); // 选择歌曲 $player->play(); // 开始播放
In order to make the code logic clearer and more readable, we must be good at encapsulating functionally independent code blocks into functions. According to this design idea, we can extract the conditional branches and place them in a separate method in a class. This class can be called the simple factory pattern.
Definition of simple factory pattern: A class can obtain different instances based on different parameters. Generally, these created instances have the same parent class.
Static factory pattern: Generally, we set the methods used to create different instances in the simple factory pattern as static methods to avoid creating multiple identical instances.
Let’s rewrite the above code using the simple factory pattern
class MusicPlayerFactory { public static function create ($type) { if ($type == 'QQ') { $player = new QQPlayer(); } else if ($type == 'Wy') { $player = new WyPlayer(); } else if ($type == 'KG') { $player = new KGPlayer(); } else { $player = null; } return $player; } } // 业务代码修改如下 $player = MusicPlayerFactory:create('QQ'); $player->on(); // 打开播放器 $player->choiceMusic('我不配'); // 选择歌曲 $player->play(); // 开始播放
For the above simple factory pattern, if we need to add a new music player, we will definitely modify it The create method of MusicPlayerFactory is somewhat inconsistent with the "opening and closing principle". There are not many such conditional branches, and the creation of other classes is also very simple. It is completely possible to use the simple factory pattern. If you have to remove the if branch logic and make it comply with the "opening and closing principle", then you can use the factory method to achieve it. For factory methods, it is not necessarily better than the simple factory pattern. Although its scalability is better, it sacrifices readability.
Factory method pattern
Definition: In the factory method pattern, the factory parent class is responsible for defining the public interface for creating product objects, and the factory child The class is responsible for generating specific product objects. The purpose of this is to delay the instantiation operation of the product class to the factory subclass, that is, the factory subclass is used to determine which specific product class should be instantiated.
Now we use "polymorphism" to eliminate the if branch structure of the simple factory pattern above. The implemented code is as follows:
interface IMusicPlayerFactory { static function create (); } class QQPlayerFactory implements IMusicPlayerFactory { public static function create () { return new QQPlayer(); } } class WyPlayerFactory implements IMusicPlayerFactory { public static function create () { return new WyPlayer(); } } class KGPlayerFactory implements IMusicPlayerFactory { public static function create () { return new KGPlayer(); } } // 业务代码修改如下 if ($type == 'QQ') { $player = QQPlayerFactory::create(); } else if ($type == 'Wy') { $player = WyPlayerFactory::create(); } else if ($type == 'KG') { $player = KGPlayerFactory::create(); } else { throw new \Exception('...'); } $player->on(); // 打开播放器 $player->choiceMusic('我不配'); // 选择歌曲 $player->play(); // 开始播放
As you can see, the problem has returned to the original point, and the if conditional branch structure appears again in the business code. So how to solve this problem?
We can create a simple factory for the factory class to create factory class objects. The new simple factory code is as follows:
class MusicPlayerFactoryMap { const Players = [ 'QQ' => 'QQPlayerFactory', 'Wy' => 'WyPlayerFactory', 'KG' => 'KGPlayerFactory' ]; public static function getPlayerFactory (string $type) { if (empty($type)) { return null; } return (self::Players[$type])::create(); } } // 业务代码修改如下 $palyer = MusicPlayerFactoryMap::getPlayerFactory('QQ') $player->on(); // 打开播放器 $player->choiceMusic('我不配'); // 选择歌曲 $player->play(); // 开始播放
As you can see, using the factory pattern, the structure becomes much more complex than before. We only recommend using the factory method pattern if the process of creating an instance is copied.
Abstract Factory Pattern
The abstract factory pattern is used in special scenarios and is rarely used. In the factory method pattern, specific factories are responsible for producing specific products, and each factory corresponds to a specific product. But sometimes, we need a factory that can create multiple product objects instead of a single product.
Let’s take a look at an example: The target computer factory is responsible for producing computers for sale. We know that a computer is composed of a host, a keyboard, a monitor and a mouse. Currently, the Target Computer City only produces three types of computers, low-profile, mid-range and high-profile. Computers with different configurations use different host brands, monitor brands, etc. of.
The hosts currently include: Kirin host, Thunder host, Winter host
The keyboards currently include: Rapoo, Logitech, Razer
The monitors currently include: aoc, hkc, BenQ
Mouses currently include: Logitech, Spirit Snake, and Founder
The top version of the computer is composed of Kirin host, Rapoo keyboard, AOC monitor, and Logitech mouse, and the mid-range version is composed of...
The code for the host is as follows:
interface Host { static function createHost (); } class DrHost implements Host { public static function createHost() { echo '创建冬日主机' . PHP_EOL; } } class QlHost implements Host { public static function createHost() { echo '创建麒麟主机' . PHP_EOL; } } class LtHost implements Host { public static function createHost() { echo '创建雷霆主机' . PHP_EOL; } }
Similarly, to create a keyboard, monitor, and mouse, the code will not be posted here.
Now, we define an interface for creating computers.
interface ComputerFactory { static function createHost (); static function createKeyboard (); static function createMonitor (); static function createMouse (); }
Then complete three specific factories for creating low-end, mid-end and high-end computers.
class GreatComputerFactory implements ComputerFactory { public static function createHost() { QlHost::createHost(); } public static function createKeyboard() { LbKeyboard::createKeyboard(); } public static function createMonitor() { AocMonitor::createMonitor(); } public static function createMouse() { LjMouse::createMouse(); } } class GoodComputerFactory implements ComputerFactory { public static function createHost() { LtHost::createHost(); } public static function createKeyboard() { LjKeyboard::createKeyboard(); } public static function createMonitor() { HkcMonitor::createMonitor(); } public static function createMouse() { LsMouse::createMouse(); } } class NormalComputerFactory implements ComputerFactory { public static function createHost() { DrHost::createHost(); } public static function createKeyboard() { LsKeyboard::createKeyboard(); } public static function createMonitor() { BenqMonitor::createMonitor(); } public static function createMouse() { FzMouse::createMouse(); } }
Now you can create a specific computer
class GreatComputer { public function __construct() { echo '高配电脑' . PHP_EOL; GreatComputerFactory::createHost(); GreatComputerFactory::createKeyboard(); GreatComputerFactory::createMonitor(); GreatComputerFactory::createMouse(); } } class GoodComputer { public function __construct() { echo '中配电脑' . PHP_EOL; GoodComputerFactory::createHost(); GoodComputerFactory::createKeyboard(); GoodComputerFactory::createMonitor(); GoodComputerFactory::createMouse(); } } class NormalComputer { public function __construct() { echo '低配电脑' . PHP_EOL; NormalComputerFactory::createHost(); NormalComputerFactory::createKeyboard(); NormalComputerFactory::createMonitor(); NormalComputerFactory::createMouse(); } }
The above is the detailed content of Understand simple factories, factory methods, and abstract factories in one article. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.