A simple example of java Singleton Mode

Source: Internet
Author: User

Singleton mode: used to ensure that a class has only one instance during a certain degree of Operation

Advantage: to save resources as much as possible

Application scenarios

--------------------

The Singleton mode is implemented by modifying the access permissions of the constructor.

For example

Package com. lixiyu; public class TestExample1 {public static void main (String [] args) {System. out. println ("create SHENMA 1 object:"); SHENMA shenma1 = SHENMA. getInstance (); // create object shenma1.getName (); // output name System. out. println ("create SHENMA 2 object:"); SHENMA shenma2 = SHENMA. getInstance (); // create object shenma2.getName (); // output name System. out. println ("create SHENMA 3 object:"); SHENMA shenma3 = SHENMA. getInstance (); // create object shenma3.getName (); // output name }}

Create a shenma class to describe it.

Package com. lixiyu; public class SHENMA {private static SHENMA shenma = null; // declare a reference to a class SHENMA private SHENMA () {// privatize the constructor} public static SHENMA getInstance () {if (shenma = null) {shenma = new SHENMA ();} return shenma;} public void getName () {System. out. println ("this is a good thing ");}}

You only need to create a new instance once to solve the problem.

public static SHENMA getInstance(){    if(shenma==null){        shenma=new SHENMA();    }    return shenma;}

The Singleton mode also has many writing methods, which are just one of them. We will record them later in our studies.

This article is from the "ToBeContinued" blog, please be sure to keep this source http://leexy.blog.51cto.com/4136883/1304452

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.