search
HomeJavajavaTutorialExplanation of singleton pattern in java design patterns

Explanation of singleton pattern in java design patterns

Jul 21, 2017 pm 05:03 PM
javamodelDesign Patterns

I learned that there are 23 design patterns in Java. Design patterns are summaries of code experience that are known to most people, used repeatedly, and are conventional. Each design pattern represents a problem that will occur repeatedly in the project, so the reasonable use of design patterns can perfectly solve many problems.

It is necessary to learn Java design patterns. Although inheritance and interfaces have not been learned in object-oriented, the singleton pattern in the 23 design patterns can already be understood.

Singleton object is a commonly used design pattern. In Java applications, a singleton object can ensure that only one instance of the object exists in a JVM. There are two specific forms of expression:

package 面向对象;//单例设计模式第一种public class Singleton 
{public static void main(String[] args)
    {
    SingletonDemo a=SingletonDemo.getInstance();
    }
}class SingletonDemo
{private static SingletonDemo a =null;private SingletonDemo(){}public static SingletonDemo getInstance()
    {if(a==null)
        {
            SingletonDemo a=new SingletonDemo();
        }return a;
    }
}

This way can be seen that new objects are created only when the method is called, but it is easy to cause problems when using multiple threads. , so the following method is generally used for development.

 1 package 面向对象; 2  3 public class Singleton_2 
 4 { 5     public static void main(String[] args) 6     { 7         Singleton_2Demo a=Singleton_2Demo.getInstance(); 8     } 9 }10 11 class Singleton_2Demo12 {13     private Singleton_2Demo(){}14     private static Singleton_2Demo a=new Singleton_2Demo();15     public static Singleton_2Demo getInstance()16     {17         return a;18     }19 }

This method is simple and there is no need to consider multi-threading issues

Through this design pattern, we can learn more about the previous The object-oriented exercise I wrote was adjusted to implement the singleton pattern.

Original code:

package 面向对象; class Student 
{    private String name;private int number;private String sex;private boolean learn;private String a;
    Student()
     {
         name="未知";
         number=000;
         sex="未知";
         learn=false;
         a="未知";
     }     public void setName(String name)
     {         this.name=name;
     }     public void setNumber(int number)
     {         this.number=number;
     }     public void setSex(String sex)
     {         this.sex=sex;
     }     public void setLearn(boolean learn)
     {         this.learn=learn;
     }     void scan()
    {if(this.learn==true)
        {
            a="在学习";    
        }else{
            a="不在学习";
        }    
         System.out.print("姓名:"+this.name+" 学号:"+this.number+" 性别;"+this.sex+" 是否在学习:"+a);
    }
    
} class Data
 {     public static void main(String[] arg)
     {
         Student XiaoMin=new Student();
         XiaoMin.setName("小明");
         XiaoMin.setNumber(13023);
         XiaoMin.setSex("男");
         XiaoMin.setLearn(true);
         XiaoMin.scan();
     }
 }

Single case mode:

package 面向对象;//实现单例设计模式
 class Student_1 
{    private String name;private int number;private String sex;private boolean learn;private String a;     private Student_1()
     {
         name="未知";
         number=000;
         sex="未知";
         learn=false;
         a="未知";
     }     private static Student_1 b=new Student_1();     public static Student_1 getInstance()
     {         return b;
     }     public void setName(String name)
     {         this.name=name;
     }     public void setNumber(int number)
     {         this.number=number;
     }     public void setSex(String sex)
     {         this.sex=sex;
     }     public void setLearn(boolean learn)
     {         this.learn=learn;
     }     void scan()
    {if(this.learn==true)
        {
            a="在学习";    
        }else{
            a="不在学习";
        }    
         System.out.print("姓名:"+this.name+" 学号:"+this.number+" 性别;"+this.sex+" 是否在学习:"+a);
    }
    
} class Data_2
 {     public static void main(String[] arg)
     {
         Student_1 XiaoMin=Student_1.getInstance();
         XiaoMin.setName("小王");
         XiaoMin.setNumber(13023);
         XiaoMin.setSex("男");
         XiaoMin.setLearn(true);
         XiaoMin.scan();
     }
 }

The above is the detailed content of Explanation of singleton pattern in java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)