Home > Backend Development > PHP Tutorial > What is factory pattern?

What is factory pattern?

藏色散人
Release: 2023-04-05 20:34:02
forward
7202 people have browsed it

Factory pattern (factory pattern) is our most commonly used instantiation object pattern. It is a pattern that uses factory methods to replace new operations. The famous Jive forum uses the factory pattern extensively. The factory pattern can be seen everywhere in the Java program system. Because the factory pattern is equivalent to new for creating instance objects, we often generate instance objects based on class Class, such as A a=new A().

Factory mode is also used to create instance objects, so you need to be careful when doing new in the future. Can you consider using factory mode? Although doing so may require more work, it will bring problems to your system. Greater scalability and minimal modifications.

<?php
//汽车类
class car{
    public function run(){
    echo &#39;car run .....&#39;;
    }
}
class bus{
    public function run(){
        echo &#39;bus run .....&#39;;
    }
}
//创建一个汽车工厂类用于生产汽车对象
class carFactory{
    public static function getACar($type){
if($type == &#39;car&#39;){
    return new car();
}else{
    return new bus();
}
    }
}
//调用演示
$car = carFactory::getACar(&#39;bus&#39;);
$car->run();
Copy after login

As the project progresses, the bus class and the car class may "give birth to many sons", so we have to instantiate these sons one by one. What's worse, we may also have to instantiate the previous ones. The code is modified, such as modifying the class name or file name of the car or setting a constructor for the car or bus. If we do not use the engineering mode, we will need to modify the corresponding calling files and codes (forgot how to cause a bug!!) .

But if you consciously use the factory pattern from the beginning, these troubles will be gone.

The above is the detailed content of What is factory pattern?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:hcoder.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template