JAVA single-Instance design pattern

Source: Internet
Author: User

/*Design Patterns: The most effective solution for this type of problem Java 23 Design Patterns Singleton design pattern: Solve A class that only exists in memory an object how to make a class exist in memory only one object? 1, prohibit other applications, through this class to create object 2, since the external cannot create objects through this class, we want to use the object, we can create this class object 3, in order to other applications to access to the object created in this class, I need to provide a way for the outside world how to use code to show: 1 , privatization construction Method 2, create this class in this Class object 3, access to the outside world to provide a method of the single-instance design mode when to use? In the case of a project, if you want a class that requires only one object, then we'll use the singleton design pattern below is a simple example of a singleton design pattern.*/classperson{String name; PrivatePerson () {}StaticPerson p =NewPerson ();  Public StaticPerson getinstance () {returnp; }} Public classtest{ Public Static voidMain (string[] args) {person A=person.getinstance (); A.name= "Xiao Ming"; Person B=person.getinstance ();    System.out.println (B.name); }}/*extension of Knowledge: 1, in the class, you can new the current class as an object 2, in the class new object, can be set to privatize, or public, such as 3, Direct use of the class name. Static methods can also be assigned to other variables, after assignment, the equivalent of new to the class object, the object can access the class of other member properties, methods, etc.*/

JAVA single-Instance design pattern

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.