PHP Basic design mode Daquan (registration tree, factory, single-row mode), design mode single-_php tutorial

Source: Internet
Author: User

PHP Basic design mode Daquan (registered tree mode, Factory mode, single row mode), design mode single


Not much nonsense to say, first introduce the registered tree mode and then introduce the Factory mode finally give you introduce a single-row mode, this article is written in detail, together to learn it.

PHP Registration Tree Mode

What is a registered tree mode?

Registration tree mode is also called registration mode, Registrar mode. The reason I am here to make a sentimental name is because I feel that the name of the registration tree is easier to understand. Like the first two articles, we still start with the name. The registration tree mode is designed by registering the object instance on a global object tree, and then picking the pattern from the object tree when needed. This reminds me of the childhood buy candied fruit, sell candied fruit will candied fruit inserted in a big pole, people buy when take down. The difference is, the registration tree mode pick down will have, can pick a lot of times, candied fruit pick once no ...

Why should I use the registration tree mode?

The singleton pattern solves the problem of how to create a unique object instance throughout the project, and the factory pattern solves the method of not building the instance object through new. So what's the problem with registering tree mode? Before considering this issue, it is necessary to consider the limitations that the first two models are currently facing. First, the process of creating a unique object in a singleton pattern also has the judgment that the object exists. exists returns the object, does not exist, creates the object, and returns. Each time you create an instance object, there is a layer of judgment. The factory model is more about the problem of extended maintenance. In general, singleton patterns and factory models can produce more reasonable objects. How is it convenient to call these objects? And in the project so set up objects like stragglers, inconvenience management arrangements AH. Thus, the registration tree pattern emerges. Whether you're using a singleton or factory or a combination of both, all of them are "plugged in" to the registration tree. When I use an object, I just take it from the registration tree. This is as convenient and practical as we use global variables. And the registration tree mode provides a very good idea for other modes.

How do I implement a registration tree?

With the above description, we seem to find a solution easily. First, we need a class as a registered tree, which is beyond doubt. All objects are "inserted" onto the registration tree. This registration tree should be played by a static variable. And this registration tree should be a two-dimensional array. This class should have a method (set ()) that inserts an object instance, and if so, there should be a way to undo the object instance (_unset ()). Of course, the most important thing is to have a method for reading the object (get ()). With these, we can happily complete the registration tree mode ~ ~ ~

Let's make a small combination of the three patterns below. Simply creating an instance object is far less complex, but in large projects, convenience is self-explanatory.

<?php//Create a singleton class single{public $hash; static protected $ins =null; final protected function __construct () {  $this- >hash=rand (1,9999); } static Public Function getinstance () {  if (self:: $ins instanceof Self) {   return self:: $ins;  }  Self:: $ins =new self ();  Return self:: $ins; }}//Factory mode class randfactory{public static function factory () {  return single::getinstance ();}} Register tree class register{protected static $objects; public static function set ($alias, $object) {self  :: $objects [$alias] = $object; public static function Get ($alias) {  return self:: $objects [$alias],} public static function _unset ($alias) {  Unset (self:: $objects [$alias]); }}register::set (' Rand ', Randfactory::factory ()), $object =register::get (' rand ');p Rint_r ($object);

At this point, three modes of the design are complete. The pattern design itself will complement each other, and when it comes to other patterns, one or more of the other design patterns will be used.

A mode does not matter, I believe that the depth of programming, will produce a sudden sense of surprise, is willing to gentlemen and I progress together.

PHP Factory mode

So what is the factory model?

Judging from the name, there seems to be no clue. Factory mode, and production-related? Or is it related to the production process? Does it have to do with the factory leadership? Is it related to the leading secretary? Secretary... Well, not suspense, the so-called factory model is really related to production. What does it produce? The production is an instance object. What equipment is produced? Produced through a factory class. How to produce it? The factory class calls its own static method to produce an object instance.

The factory model has a key construct, named Factory static method according to general principle, however this is only a principle, although the factory method can be arbitrarily named this static can also accept arbitrary data parameters, must return an object.

Why use Factory mode?

Many people who have not contacted the factory model can not help asking, why do I have to take so much effort to construct a factory class to create objects? We can consider such a simple question without applying those easy-to-maintain, extensible, and so on. If you are in a project, we create an object from a class. At the time of completion or completion, to extend the function, it is found that the original class name is not appropriate or that the class needs to add constructor parameters to implement the function extension. Holy shit! I've created a whole bunch of object instances through this class. Oh, I'm going to have to change one more? We now feel the "high cohesion and low coupling" of the profound. No problem, the factory method can solve this problem.

Think again, I want to connect the database, in PHP there are several methods, MySQL extension, mysqli extension, PDO extension. I just want an object to be used in the future operation, depending on which, depending on the situation. Since you are all connected to the database, you should have the same functionality, make connections, query, disconnect ... (The importance of the interface is shown here.) In a word, these methods should be "united and consistent". How to achieve it? Take advantage of Factory mode.

How is the factory model implemented?

With respect to the singleton pattern, we have provided enough information, factory class, and static methods inside the factory class. In the static method, the object instance that needs to be created in new is done. Of course, considering the second question above, according to the parameters of static method of factory class, we can make a simple judgment. Tube you with If. else.. or switch. Case: It's good to be able to quickly and efficiently decide which class to create. Finally, be sure to remember that the factory class static method returns an object. Not two, not three.

Basic Factory class:

The class to create the object instance class myobject{}//factory class Myfactory{public static function factory () {return new MyObject ():}} $instance = Myfactory::factory ();

A slightly more complex factory pattern:

<?phpinterface transport{Public Function Go (); Class Bus implements transport{public function go () {  echo Bus stops at every station;}} Class Car implements transport{public function go () {  echo "Car runs Fast";}} Class Bike implements transport{public function go () {  echo "Bike slower";}} Class transfactory{public static function factory ($transport) {  switch ($transport) {case   ' bus ':    return New Bus ();    break;   Case ' car ':    return new car ();    break;   Case ' bike ':    return new bike ();    break;  } }} $transport =transfactory::factory (' car '); $transport->go ();

When you need a factory static method for factory () , don't be silly to name the factory class factory . Why, Why? Don't forget the same name constructor thing.

Finally, a little bit of feeling, a lot of novice compared above his business, just will be if. Else..,session,cookie is going to be a little taller. Talk with people easily extensibility, maintainability and so on, as for instance, it will be a temporary speechless. Sometimes feel, regardless of their own code or to learn from others, are in "the crowd to find him thousands of degrees," the real practical study, suddenly look back, "the person is in the lights dim place," The big Call: "The original TM is * * * AH."

I dare not admit that I will pattern design, I am also a less than a year of beginners, sharing blog just want to record their learning process, can get to know is more than wish. If you can help others, it's better.

PHP Single-row mode

What is a pattern design?

A beginner will be fooled by the name of the tall one at first. For the veteran with rich programming experience, pattern design is ubiquitous. Many of the frames of engagement are based on a variety of pattern designs. Simply put, in the process of writing code in the beginning often contact is process-oriented, simple BASIC programming. This time we tend to pursue the code to achieve a certain function is all right. How redundant the code is, whether the code is reusable, how efficient it is, and how well it can be achieved. But what really applies to real-world adoption is the code that is efficient, reusable, and easy for the team to develop. Based on these factors, you can't simply name the function as practiced hand and place the script casually. Pattern design tells you to provide a way for people to organize code, implement reusable code, make it easier for others to understand, and ensure code reliability.

In all pattern design, there are three basic design patterns, Singleton mode, Factory mode, registered tree mode, other patterns are often based on these patterns, the following is a singleton mode.

What is a singleton mode?

According to this name, it is easy to see that the Singleton pattern refers to the design pattern of only one object instance throughout the application.

Why use singleton mode?

PHP often deals with databases, which is not what we want to see if the connection objects are frequently established in the application and new operations are made, which consumes aniseed system memory resources. Moreover, in a team-work project, the singleton model can effectively avoid the different programmers new their own objects, resulting in artificial system consumption.

How to set up a singleton mode?

When you see this problem, believe that good programmers are likely to try to create singleton patterns on their own, rather than waiting for the experience of their predecessors. Different from other Bo friends to tell you what kind of pattern is a singleton mode, I am more willing and have the basic experience of object-oriented programming you consider how to set up a singleton mode.

We start with the topic, the singleton pattern is the design pattern of only one object instance. This is a very painful thing to do. The classes we normally create are not objects that can be created, or objects that cannot be created (abstract classes). It is necessary to have a class to create an object, and it cannot be an abstract class. This class prevents others from creating functions more than once. We naturally consider the beginning of the constructor function. However, each new operation invokes the constructor, which means that the object instance is created more than once. This is contrary to our original design. It is important to state that the constructor is private or protected in order to resolve the problem.

The constructor is declared private or protected, which is doomed to create an instance object by using new method. And we find that after this step, the prospect of solving the problem becomes clear. Why is it? Now that you can't create an object instance from the new method, we can only create an instance of the object through a method within the class. At this point we face an interesting problem of having chickens or eggs first. We tend to be the method of invoking the object after the object is created, and we need to invoke the method inside the class to create the object. The solution to a method that is not affected by the creation of an object is undoubtedly the use of the keyword--static.

What does it do to create a static method within a class? Regression topic: Make sure that only one instance object is created. How do you make sure there's only one? This is very simple, if you judge Ah. If there is a direct return, there is no one to create. Of course, this instance object is a static property of the class. At this point, the single-instance mode requires the completion of the functional implementation. Is it really done yet? If there is a class that inherits this class, declare the construction method public that's not a bad thing? It is necessary to add the final keyword before constructing the method.

Finally paste the single code, code interpretation is on the top ~ ~

<?phpclass single{public $hash; static protected $ins =null;  Final protected function __construct () {  $this->hash=rand (1,9999);} static public Function getinstance () {  if (self:: $ins instanceof Self) {   return self:: $ins;  }  Self:: $ins =new self ();  Return self:: $ins; } }

The singleton pattern itself is not complex, but requires deep understanding. Many beginners will still sigh: crouching groove, the construction method is not always public AH ~ Crouching trough can also not create objects through new AH ~ Actually I want to say, regardless of the construction method is declared as public,private or protected, the final creation of the object will be called. Always is new creates an object instance, and the singleton mode creates the object with new, just in a different place, from outside the class to the class.

Finally to the study of a variety of subtle pattern design programmer said admire ~ ~

http://www.bkjia.com/PHPjc/1050137.html www.bkjia.com true http://www.bkjia.com/PHPjc/1050137.html techarticle PHP Basic design mode Daquan (registered tree mode, Factory mode, single-row mode), design mode single-row nonsense not much to say, first introduce the registered tree mode and then introduce the Factory mode finally give ...

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