PHP Basic Design Pattern Encyclopedia (registered tree mode, Factory mode, Single-column mode) _php instance

Source: Internet
Author: User
Tags abstract rand

Nonsense not to say, first to introduce the registration tree model and then introduce the factory model finally to introduce a single mode, this article is written in detail, together to learn.

PHP Registration Tree Mode

What is the registration tree mode?

Registration tree mode is also called registration mode, the Registrar mode. The reason I am here to make a name for it is because I feel that the name of the registered tree is easier to understand. Like the first two articles, we still start with the name.   The registration tree mode is the pattern design method that is picked from the object tree when it is required by registering the object instance on a global object tree. This reminds me of a child to buy gourd, selling gourd will gourd inserted in a big pole, people buy when they take down. The difference is that the registration tree mode to pick down there will be, can pick a lot of times, gourd picked once there is 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 how to create an instance object without new. So what does the registration tree model want to solve?  Before we consider this issue, we still need to consider the limitations of the first two models that are currently under way. First, the process of creating a unique object in a single pattern also has a judgment that determines whether an object exists. exists, the object is returned, and the object is created and returned. Every time you create an instance object, there is a level of judgment. The factory model is more concerned with the issue of extended maintenance. In general, a single case model and a factory model can produce more reasonable objects. How is it convenient to call these objects? And in the project so set up objects like stragglers, it is inconvenient to co-ordinate management arrangements AH. Therefore, the registration tree model arises. Whether you're using a single model, a factory model, or a combination of the two objects, all of them are "plugged into" the registration tree. When I use an object, just take it from the registration tree. This is as convenient and practical as we use global variables. And the registration tree model provides a very good idea for other schemas.

How do I implement a registration tree?

By the above description, we seem to have found a solution easily. First of all we need a class as a registration tree, which is beyond doubt. All objects are "inserted" into the registration tree. This registration tree should be a static variable to act as. And the registration tree should be a two-dimensional array. This class should have a method for inserting an instance of an object (set ()), which should have a method to undo the object instance (_unset ()) when it is corresponding. Of course, the most important thing is that you also need to have a method of reading the object (get ()). With these, we can happily complete the registration tree mode ~ ~ ~

Here are three modes to make a small combination. Simply creating an instance object is far less complex, but in the case of large projects, convenience is self-evident.

<?php
//Create a single instance
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 ');
Print_r ($object);

At this point, three models of the design is finished. The pattern design itself will complement each other, introducing other patterns later, more or less will use one or more other design patterns.

A mode does not understand, I believe that the depth of programming, will produce a sudden surprise, I would like to make progress together.

PHP Factory mode

So what is the factory model?

From the name point of view, it seems to see no clue. Factory model, and production related? Or is it related to the production process? Does it have something to do with the factory leadership? With the Secretary of the leadership?     Secretary... Well, no 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 through? Produced by 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, which is named Factory static method according to general principles, but this is only a principle, although the factory method can arbitrarily name this static and can accept parameters of arbitrary data, must return an object.

Why use Factory mode?

Many people who have not been exposed to the factory model can not help but ask, why do I have so much effort to construct the factory class to create objects? We can consider such a simple question without applying those easy to maintain, scalable, and so on. If in the project, we create the object through a class. In the near completion or completion, to extend the function, it is found that the original class class name is not appropriate or found that the class needs to add constructor parameters to achieve the function extension. Holy shit! I've created a whole bunch of object instances through this class. Ah, I also want to one to change it? We now feel the "high cohesion low coupling" of profound. No problem, the factory method can solve the 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 for later operations, specific to which, depending on the situation. Since you are all connected to the database operation, you should have the same function, establish the connection, query, disconnect ... (The importance of the interface is shown here.) In a nutshell, these methods should be "united and consistent". How to achieve it? Use the factory model.

How is the factory pattern implemented?

Relative to the single case pattern, we provide enough information about the factory class and the static method inside the factory class. static method inside the new object instance that needs to be created is done. Of course, considering the second question above, according to the factory class static method parameters, we simply make a judgment. If you use the IF. else.. or switch. Case ..., it's nice to be able to quickly and efficiently finish the job of deciding 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:

Class classes
myobject{
}
 //factory class
myfactory{public
static function factory () {
to create an object instance return new MyObject ():
 }
}
$instance =myfactory::factory ();

A slightly more complex factory model:

<?php
Interface transport{public
 function Go ();
}
Class Bus implements transport{
 the public Function go () {
  echo "stops at every stop";
 }
Class car implements transport{the public
 function goes () {
  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 to
    new Bus ();
    break;
   Case "Car": Return to
    new car ();
    break;
   Case ' bike ': Return to
    new bike ();
    break;
  }
}} $transport =transfactory::factory (' car ');
$transport->go ();

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

Finally, let's talk about some feelings, many beginners compare Yangaoshoudi, just will have the IF. Else..,session,cookie is going to be a little tall. Talk with people at all moments scalability, maintainability and so on, as for instance, will be tongue-tied. Sometimes feel that no matter how they write code or with others to learn, are in the "public search for his thousand degrees," when the real practical study, suddenly looking back, "the man is in the lights dim place", Big shout: "Originally this TM is * * *."

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

PHP single row mode

What is the pattern design?

The beginner will be intimidated by the tall name at first. And for the veteran with rich programming experience, the pattern design is everywhere. Many of the contact frameworks are based on various patterns of design. To put it simply, in the process of writing code, a process-oriented, simple basic programming is often the first contact. This time we tend to pursue is that the code can achieve a function is all right. How redundant the code is, whether the code can be reused, how efficient it is, and how well it can function. However, what is really applied to the real world is that it is more efficient, reusable, and easily developed by the team. Based on these factors, you can not like practicing, casually named function name, Random place script. Pattern design tells people to organize code to provide a way to implement reusable code, make code easier to be understood by others, and ensure code reliability.

In all pattern designs, there are three basic design patterns, single case mode, Factory mode, registration tree mode, and other models are often based on these patterns, the following is a single example mode.

What is a single case mode?

By this name, it is easy to understand that a singleton pattern refers to a design pattern that has only one object instance throughout the application.

Why use a single case pattern?

PHP often deal with the database, if in the application of frequent connection objects, if the new operation, will consume aniseed system memory resources, this is not what we want to see. Moreover, in the team cooperation project, the single case pattern can effectively avoid the different programmer new own object, causes the artificial system consumption.

How do I set up a single case pattern?

When it comes to the problem, it is believed that good programmers are likely to try to create a single model on their own, rather than waiting for the experience of their predecessors. Unlike other bloggers who tell you what mode is a single case pattern, I am more willing and have the basic experience of object-oriented programming you consider how to build your own single case mode.

We start with the topic, the singleton pattern is a design pattern with only one object instance. This is a very painful thing to have. The classes we normally create are not those that create many objects, but those that cannot create objects (abstract classes). To create an object you need a class that is necessary and cannot be an abstract class. This class prevents others from creating functions more than once. We naturally consider starting with the constructor. However, each new operation calls the constructor, which means that the object instance is created multiple times. This is contrary to our original design. It is important here to affirm that the constructor is private or protected to solve this problem.

Constructors are declared private or protected this is doomed to not create an instance object through the new method. And we find that, after this step, the prospect of solving the problem becomes clear? Why, then? Since it is not possible to create an object instance through the new method, we can only create an object instance through a method within the class. This time we are faced with an interesting question of whether to have a chicken or an egg first. We tend to create objects before we call them, and we need to call methods inside the class to create objects. A solution that is not affected by the creation of an object can be invoked without a doubt that is using keyword--static.

Create a static method within a class complete what work? Regression topic: Make sure that only one instance object is created. How do you make sure there is only one? This is very simple, if the judge Ah. The existence of the words directly returned, does not exist to create one. Of course, this instance object is a static property of the class. At this point, the single example mode requires the completion of the functionality. Is it really done? If there is a class that inherits this class, the constructor method is declared public. Isn't that a bad thing? It is necessary to add the final keyword before constructing the method.

Finally paste the single example pattern code, the code explanation is above the ~ ~

<?php
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;
 } 
}

The single case model itself is not complex, but requires deep understanding. Many beginners will still sigh: horizontal groove, the original construction method is not always public ah ~ Groove can also not create objects through new AH ~ In fact, I would like to say, regardless of the construction method is declared as public,private or protected, the final creation of the object will be invoked. It's always new. Creates an object instance, and the singleton pattern also creates objects with new, just another place, from outside the class to the class.

At last, the programmers who have developed all kinds of ingenious pattern design show kneel ~ ~

Related Article

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.