PHP Classic design mode-Simple Factory mode

Source: Internet
Author: User

PHP Classic design mode-Simple Factory modepfinalIntroduced

We were going to get an instance of a class and need to use the New keyword. But if new is written directly into the business code, a class is instantiated in many places, and if there is something wrong with this class, such as changing a name (in practice, you may be more likely to modify the constructor method), then it is awkward and needs to be changed a lot.

Factory mode, as the name implies, is not to use new to obtain an instance, but to put the business class into a workshop class, by the factory (class) "Production" Out of the corresponding instance.

Realize

Simplefactory.PHP<?phpnamespace designpatterns\creational\simplefactory;classsimplefactory{ Public functionCreatebicycle ():Bicycle {return NewBicycle (); }}
Bicycle.PHP<?phpnamespace designpatterns\creational\simplefactory;classbicycle{ Public functionDriveto (string $destination) { }}

Use

$factory New  $bicycle$factory,$bicycle->driveto (' Paris ');

What kind of examples do we need to get to the factory instance method. Only one instance of a class is defined here, and you can define more.

We see that the business code does not appear in the new and that specific business class, so that the business class (class Bicycle) We can arbitrarily change, in the future, as long as in the factory class (class Simplefactory) modified once, you can be a pair of more in the place to take effect.

However, the method name $factory->createbicycle (); You have to get good, if you want to change the name, or you have to change a number of places.

Summarize

The Rule factory class must have a factory method; The factory method must be able to return an instance of another class; only one instance can be created and returned at a time;

PHP Classic design mode-Simple Factory mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.