Home Backend Development PHP Tutorial PHP pattern design singleton pattern

PHP pattern design singleton pattern

Jul 30, 2016 pm 01:30 PM
new private protected public self

 What is pattern design? Beginners will be intimidated by this lofty name at first. For veterans with rich programming experience, pattern design is everywhere. Many contact frameworks are designed based on various patterns. To put it simply, in the process of writing code, what you often come into contact with at the beginning is process-oriented, simple and basic programming. At this time, what we often pursue is that everything will be fine if the code can achieve a certain function. It doesn’t matter how redundant the code is, whether it is reusable, or how efficient it is, as long as it can achieve the function. However, what is really applied in practice and is more adopted by everyone is the code that is efficient, reusable, and easy for team development. Based on these factors, you cannot just name functions and place scripts casually like you are practicing. Pattern design advice is to provide people with an idea for organizing code, to achieve reusable code, to make the code easier to understand by others, and to ensure code reliability.

 In all pattern designs, there are three basic design patterns, singleton pattern, factory pattern, and registration tree pattern. Other patterns are often based on these patterns. Today we bring the singleton pattern.

What is singleton pattern?

Based on this name, we can easily understand that the singleton pattern refers to a design pattern in which there is only one object instance in the entire application.

Why use singleton mode?

php often deals with databases. If you frequently establish connection objects and perform new operations in your application, a large amount of system memory resources will be consumed, which is not what we want to see. Furthermore, in team cooperation projects, the singleton mode can effectively prevent different programmers from newing their own objects, causing artificial system consumption.

 How to create a singleton pattern?

When I see this problem, I believe that excellent programmers are likely to try to create a singleton pattern according to the requirements instead of waiting for the experience of their predecessors. Unlike other bloggers who tell you what kind of pattern is a singleton pattern, I prefer to think about how to build a singleton pattern yourself with you who have basic experience in object-oriented programming.

Let’s start from the title first. The singleton pattern is a design pattern with only one object instance. This is very painful. The classes we usually create can either create many objects or cannot create objects (abstract classes). To create an object, a class is required, and it cannot be an abstract class. This class is to prevent others from creating functions multiple times. We naturally considered starting with the constructor. However, each new operation will call the constructor, which means that the object instance will be created multiple times. This is contrary to our original design intention. Be sure to declare the constructor as private or protected here to solve this problem.

  If the constructor is declared as private or protected, it is destined to be unable to create an instance object through the new method. And we found that after this step of processing, the prospects for solving the problem became clear? why? Since object instances cannot be created through the new method, we can only create object instances through methods within the class. At this time we are faced with an interesting chicken or egg problem. We often call the object's method after creating the object. At this time, we need to call the method in the class to create the object. The solution to a method that can be called regardless of whether the object is created is undoubtedly to use the keyword --static.

 What does creating a static method within a class accomplish? Back on topic: Make sure you only create one instance object. How to ensure that there is only one? This is very simple, just judge if. If it exists, return it directly. If it doesn't exist, create one yourself. Of course, this instance object is a static property of the class. At this point, the functions required by the singleton mode are implemented. Is it really completed? Not yet~ If a class inherits this class, wouldn't it be a bad thing to declare the constructor as public? Then it is necessary to add the final keyword before the constructor method.

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

<?<span>php
</span><span>class</span><span> Single{
    </span><span>public</span><span>$hash</span><span>;
    </span><span>static</span><span>protected</span><span>$ins</span>=<span>null</span><span>;
    </span><span>final</span><span>protected</span><span>function</span><span> __construct(){
        </span><span>$this</span>->hash=<span>rand</span>(1,9999<span>);
    }

    </span><span>static</span><span>public</span><span>function</span><span> getInstance(){
        </span><span>if</span> (self::<span>$ins</span><span> instanceof self) {
            </span><span>return</span> self::<span>$ins</span><span>;
        }
        self</span>::<span>$ins</span>=<span>new</span><span> self();
        </span><span>return</span> self::<span>$ins</span><span>;
    } 
}</span>
Copy after login

 The singleton mode itself is not complicated, but it requires in-depth understanding. Many beginners still sigh: Damn it, the constructor is not always public~ Damn it, you can create objects without using new~ In fact, the author wants to say that no matter whether the constructor is declared as public, private or protected, the object is finally created will be called whenever. New is always used to create object instances. Singleton mode also uses new to create objects, but it just changes the place, from outside the class to inside the class.

Finally, I would like to express my admiration to the programmers who have developed various exquisite pattern designs~~

The above introduces the singleton mode of PHP mode design, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

What is the difference between the developer version and the public version of iOS? What is the difference between the developer version and the public version of iOS? Mar 01, 2024 pm 12:55 PM

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

What does private mean in java What does private mean in java Nov 24, 2022 pm 06:27 PM

In Java, private means "private" and is an access control modifier used to modify classes, properties and methods. Class members modified with private can only be accessed and modified by the methods of the class itself, and cannot be accessed and referenced by any other class (including subclasses of the class); therefore, the private modifier has the highest level of protection.

How to use self in Python How to use self in Python May 17, 2023 pm 10:40 PM

Before introducing the usage of self in Python, let’s first introduce the classes and instances in Python. We know that the most important concepts of object-oriented are classes and instances. Classes are abstract templates, such as abstract things like students. , can be represented by a Student class. Instances are specific "objects" created based on classes. Each object inherits the same methods from the class, but its data may be different. 1. Take the Student class as an example. In Python, the class is defined as follows: classStudent(object):pass(Object) indicates which class the class inherits from. The Object class is all

Detailed explanation of private access modifiers for Java functions Detailed explanation of private access modifiers for Java functions Apr 25, 2024 pm 04:48 PM

Private is a Java access modifier that limits the accessibility of a function to only the class in which it is defined, including: the function cannot be accessed in other classes. The function is also not accessible in subclasses.

What is the difference between make and new in go language What is the difference between make and new in go language Jan 09, 2023 am 11:44 AM

Differences: 1. Make can only be used to allocate and initialize data of types slice, map, and chan; while new can allocate any type of data. 2. New allocation returns a pointer, which is the type "*Type"; while make returns a reference, which is Type. 3. The space allocated by new will be cleared; after make allocates the space, it will be initialized.

Java function access permission modifier public usage guide Java function access permission modifier public usage guide Apr 26, 2024 am 08:39 AM

The Java public access modifier allows functions to be accessed from anywhere and is used to declare public APIs and define tools and utilities that are shared across packages or classes. The specific usage is as follows: Syntax: public return value type function name (parameter list) {...} Scenario: functions that need to be accessed from anywhere, methods in public APIs, shared tools or utilities

In Java, can we declare a top-level class as protected or private? In Java, can we declare a top-level class as protected or private? Sep 12, 2023 pm 07:21 PM

No, we cannot declare top-level classes as private or protected. It can be public or default (no modifiers). If there are no modifiers, there should be default access. Syntax //Atoplevelclass publicclassTopLevelClassTest{ //Classbody} If a top-level class is declared as private, the compiler will report an error, prompting "The modifier private is not allowed here." This means that top-level classes cannot be private, the same applies to protected access

See all articles