Home  >  Article  >  Backend Development  >  What is factory pattern?

What is factory pattern?

藏色散人
藏色散人forward
2019-04-15 16:00:197152browse

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();

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!

Statement:
This article is reproduced at:hcoder.net. If there is any infringement, please contact admin@php.cn delete