Php basic design pattern Daquan (registration tree pattern, factory pattern, single-column pattern) _ php instance

Source: Internet
Author: User
In all mode designs, there are three basic design modes: Singleton mode, factory mode, and registration tree mode. Other models are often based on these models, next, let's take a look at the basic php design model (registration tree model, factory model, and single-column model). If you need a friend, come and learn. Let's talk a little bit about it. Let's first introduce the registration tree model, then introduce the factory model, and finally introduce the single-column model. This article is very detailed. Let's take a look at it.

Php registration tree mode

What is the registration tree model?

The registration tree mode is also called the registration mode. The reason why I am here is 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 registers an object instance to a global object tree. The Pattern Design Method for picking from the object tree is required. This reminds me of the fact that when I was a child, I bought a sugar gourd. When I sold it, I inserted it on a large pole. People took it out when they bought it. The difference is that the registration tree model will be picked up many times, and the sugar gourd will not be picked once...

Why use the registration tree mode?

The Singleton mode solves the problem of creating a unique object instance in the entire project, and the factory mode solves the problem of creating an instance object through the new method. What problems does the registration tree solution solve? Before considering this problem, we still need to consider the limitations currently faced by the first two models. First, the process of creating a unique object in singleton mode also determines whether the object exists. If yes, an object is returned. If no, an object is created and a result is returned. This layer of judgment is required for each instance object creation. The factory model is more concerned with extended maintenance. In general, the singleton mode and the factory mode can produce more reasonable objects. How can we conveniently call these objects? In addition, it is difficult to make overall management arrangements for the objects set up in the project as if they were scattered. Therefore, the registration tree model emerged. Whether you are using the singleton mode, the factory mode, or the objects generated by the combination of the two, all of them are inserted to the registration tree. When I use an object, just retrieve it from the registration tree. This is as convenient and practical as using global variables. The registration tree model also provides a very good idea for other models.

How to Implement the registration tree?

Through the above description, it seems that we can easily find a solution. First, we need a class as the registration tree, which is beyond doubt. All objects are "inserted" to the registration tree. This registration tree should be acted by a static variable. The registration tree should be a two-dimensional array. This class should have a method to insert an object instance (set (). When the corresponding method is set, there should be a method to unset the object instance (_ unset ()). Of course, the most important thing is to have a get () method to read objects ()). With this, we can happily complete the registration tree model ~~~

Let's make a small combination of the three modes. Creating an instance object alone is far from that complex, but the convenience is self-evident if it is used in large projects.

<? Php // create a singleton class Single {public $ hash; static protected $ ins = null; final protected function _ construct () {$ this-> hash = rand ();} 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 );

So far, the three modes have been introduced. The design of various models will complement each other. When we introduce other models, one or more other design modes will be used more or less.

It doesn't matter if you don't understand a model. I believe that the depth of programming will surely bring a sense of surprise. I hope you can make progress together with me.

Php factory Model

So what is the factory model?

From the perspective of name, it seems that there is no clue. What is the factory model related to production? Or is it related to the production process? Is it still related to factory leaders? Is it related to the lead secretary? The secretary... I don't want to sell my customs. The so-called factory model is really related to production. What is production? An instance object is produced. Through which devices are produced? It is produced through a factory type. How can this problem be produced? The factory class calls its own static method to produce object instances.

The Factory mode has a key structure, which is named as the static method of Factory according to general principles. However, this is only a principle, although the factory method can be named arbitrarily, this static method can accept any data parameter, and an object must be returned.

Why use the factory model?

A lot of people who have never touched the factory model can't help asking, why do I have to spend so much time constructing a factory class to create objects? We can consider such a simple problem without applying such features as ease of maintenance and scalability. In the project, we create an object through a class. If you want to extend the function, you can find that the original class name is not very suitable or that you need to add constructor parameters to the class to implement function extension. Rely on me! I have created a lot of object instances through this class. Can't I change them one by one? We now feel the profoundness of "high cohesion and low coupling. No problem. The factory method can solve this problem.

I want to connect to the database. There are several methods in php: mysql extension, mysqli extension, and PDO extension. I just want to use an object for future operations. The specific operation depends on the actual situation. Since you are connecting to the database, you should have the same functions, establish connections, query, and disconnect... (the importance of the interface is shown here ). All in all, these methods should be "united and consistent ". How to implement it? Use the factory model.

How to Implement the factory model?

Compared with the singleton mode, the above provides sufficient information, static methods in the factory class and factory class. In the static method, the new object instance needs to be created. Of course, considering the second problem above, we can make a simple judgment based on the parameters of the factory-class static method. You can use if... else... or switch... case... to quickly and efficiently determine which class to create. Finally, remember that the factory class static method returns an object. Not two, not three.

Basic factory classes:

// Class MyObject {}// factory class MyFactory {public static function factory () {return new MyObject () :}}$ instance = MyFactory :: factory ();

A slightly complicated factory model:

<? Phpinterface Transport {public function go ();} class Bus implements Transport {public function go () {echo "bus stops every station ";}} class Car implements Transport {public function go () {echo "car running fast" ;}} class Bike implements Transport {public function go () {echo "bike is slow" ;}} 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 ();

The factory static method is requiredFactory ()Don't name the factory class as silly.Factory. Why? Don't forget about the same name constructor ~

Finally, let's talk about how it feels. Many new users are very eager to get started. Now, if... else..., session, and cookie are coming soon. Talking to people is prone to cloud Clouds such as scalability and maintainability. When it comes to instances, it will get stuck. Sometimes I feel that no matter whether I write code or learn from others, I am in the "Searching for him in the crowd". After studying it practically, I suddenly look back, "the man is in the dark ", shout: "This TM is ".

I dare not admit that I can design my own models. I am also a beginner in less than a year. I just want to record my learning history by sharing my blog, and I am not sure I can understand it. It would be better if it could help others ~~~

Php Single-Column Mode

What is pattern design?

At the beginning, beginners will be caught by the tall name. For laruence with rich programming experience, pattern design is everywhere. Many frameworks are designed based on various patterns. Simply put, the process-oriented and simple basic programming is often exposed at the beginning of the code writing process. At this time, we tend to pursue the goal of implementing a function by code. How redundant the code is, whether the code can be reused, and how efficient the code is. However, the code that is truly applied to reality is highly efficient and reusable and easy to develop by the team. Based on these factors, you cannot name a function name or place a script as you do with your hands. Pattern Design provides a way of thinking for people to organize code, so that code can be reused to make it easier for others to understand and ensure code reliability.

In all mode designs, there are three basic design modes: Singleton mode, factory mode, and registration tree mode. Other models are often based on these models. The following describes the singleton mode.

What is Singleton mode?

Based on this name, we can easily understand that the singleton mode refers to the design mode with only one object instance in the entire application.

Why is the singleton mode used?

Php often deals with databases. If connection objects are frequently established in applications and new operations are performed, the system memory resources will be consumed. This is not what we want to see. In other words, in a team collaboration project, the singleton mode can effectively avoid the new objects of different programmers, resulting in human system consumption.

How to Create a singleton mode?

When looking at this problem, I believe that good programmers may try to create a singleton mode as required, rather than waiting for the experience of their predecessors. Different from other bloggers, what kind of mode is Singleton mode? I prefer to think about how to build a singleton mode with basic object-oriented programming experience.

First, we start from the question. The Singleton mode is the design mode with only one object instance. This is a pain point. The classes we normally create cannot create many objects or (abstract classes) objects ). To create an object, a class is required and cannot be an abstract class. This class should prevent others from creating functions multiple times. We naturally consider starting with constructors. However, each new operation calls the constructor, that is, the object instance is created multiple times. This is contrary to our original design intention. Make sure that the constructor is private or protected to solve this problem.

The constructor is declared as private or protected, which is doomed to fail to create an instance object through the new method. What's more, we found that after this step, the prospects for solving the problem become clear? Why? Since object instances cannot be created using the new method, we can only create object instances using methods in the class. At this time, we are faced with an interesting problem of having chicken or eggs first. We usually call the object method after creating an object. At this time, we need to call the methods in the class to create an object. There is no doubt that a solution that can be called without being affected by the creation of objects is the use of the keyword-static.

What do I do when I create a static method in the class? Regression topic: make sure that only one instance object is created. How can we ensure there is only one? This is very simple. if you want to judge it. If it exists, it is returned directly. If it does not exist, create one by yourself. Of course, this instance object is a static attribute of the class. So far, the singleton mode requires the function implementation. Is it done? Not counting yet ~ If a class inherits this class and declares the constructor as public, isn't it a bad thing? It is necessary to add the final keyword before the constructor.

Finally, the Code of the singleton mode is pasted, and the code explanations are all above ~~

<?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 mode is not complex, but requires in-depth understanding. Many beginners still lament that the constructor is not always public ~ You can still create objects without using new in the slot ~ In fact, I want to say that no matter whether the constructor is declared as public, private, or protected, it will be called when the object is created. It is always new to create an object instance, and the singleton mode also uses new to create an object, just change the place, from outside the class to inside the class.

Finally, I would like to greet programmers who have developed various exquisite pattern designs ~~

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.