Home > Java > javaTutorial > What are Java design patterns? Introduction to Singleton Pattern in Java Design Patterns

What are Java design patterns? Introduction to Singleton Pattern in Java Design Patterns

不言
Release: 2018-09-12 15:51:19
Original
1642 people have browsed it

This article brings you what is Java design pattern? The introduction of the singleton pattern in Java design patterns has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface

I heard the name Design Pattern not long after I first learned programming, but because I was still a complete novice at the time, I didn’t touch it. . It wasn't until I became more familiar with simple business codes at work that I formally came into contact with design patterns. The earliest design pattern I came into contact with at that time was Factory Pattern, but this article talks about Single Case Pattern, which will be explained in the next article. As for why we explain Single-case pattern first? That’s because Single-case pattern is the simplest design pattern... . Everything always has a sequence, so it’s easy first and then difficult. Okay, enough nonsense, let’s get into the main story.

Introduction to Design Patterns

Explanation: The introduction mentioned here is the real “introduction”.

What is a design pattern

A design pattern is a set of code design experiences that are repeatedly used, known to most people, classified and cataloged.

Why use design patterns

Using design patterns is to reuse code, make the code easier to understand by others, and ensure code reliability.

Types of design patterns

There are 23 types of design patterns. According to the main classification, it can be divided into three major categories:

1. Creation-type patterns

These design patterns provide a way to hide the creation logic while creating objects. , instead of using the new operator to instantiate the object directly. This makes the program more flexible in determining which objects need to be created for a given instance.

  • Single case pattern

  • Factory pattern

  • Abstract factory pattern

  • Builder pattern

  • Prototype pattern

## 2. Structural pattern

These design patterns focus on the combination of classes and objects. The concept of inheritance is used to compose interfaces and define the way in which composed objects acquire new functionality.

  • Adapter Mode

  • Bridge Mode

  • Filter Mode

  • Composition mode

  • Decorator mode

  • Appearance mode

  • Flyweight Pattern

  • Agent pattern

3. Behavioral pattern

These design patterns pay special attention to objects communication between.

  • Chain of responsibility mode

  • Command mode

  • Interpreter mode

  • Iterator pattern

  • Mediator pattern


  • ##Memo pattern
  • Observer Pattern
  • State Pattern
  • Empty Object Pattern
  • Strategy Pattern
  • Template pattern
  • Visitor pattern
  • Principles of design pattern

The six principles of design patterns

    Opening and closing principle: open to extension, closed to modification.
  1. Richter substitution principle: a supplement to the opening and closing principle. Anywhere a base class can appear, a subclass can certainly appear. LSP is the cornerstone of inheritance reuse. Only when the derived class can replace the base class and the function of the software unit is not affected, the base class can be truly reused, and the derived class can also add new ones on the basis of the base class. Behavior.
  2. Dependency Inversion Principle: Programming for interfaces relies on abstraction rather than concreteness.
  3. Interface isolation principle: Try to use multiple isolated interfaces in order to reduce the coupling between classes.
  4. Demeter's Law: An entity should interact with other entities as little as possible, making the system functional modules relatively independent.
  5. Principle of synthesis and reuse: Try to use synthesis/aggregation instead of inheritance.
  6. Singleton mode

What is singleton mode

Ensure that there is only one instance of a certain class in a system and that the instance is easy to access from the outside world. For example, the Task Manager in the Windows interface can be regarded as a singleton.

Usage scenarios of singleton mode

The more commonly used ones in programs are

Database connection pool

,Thread pool,Log objectetc. Using singleton mode

When we first learned

single mode

, we basically came into contact with these two modes: hungry Chinese style and full Chinese style (lazy Chinese style) ). Let’s first take a look at the implementation of these two modes.

hunger style

Define a private constructor, set its own instance object as a private property, add static and final modifiers, and then pass the public Static method calls return instances.

 class SingletonTest1 {  

    private SingletonTest1() {  
    }  
    private static final SingletonTest1 instance = new SingletonTest1();  

    public static SingletonTest1 getInstance() {  
        return instance;  
    }  
}
Copy after login

满汉style

Define a private constructor, define a static private variable of the class, and then define a public static method to null the value of the class Judgment, return directly if not empty, otherwise reconstruct one.

class SingletonTest2 {

     private SingletonTest2() {   
     }   

     private static SingletonTest2 instance;   

     public static SingletonTest2 getInstance() {   
         if (instance == null) {
            instance = new SingletonTest2();
        }   
         return instance;   
     }   
 }
Copy after login

简单的介绍了这两种的模式,然后我们再来看看这两种模式的优缺点吧。
饿汉式

  • 优点:写起来很简单,并且不会因为不加synchronized关键字而造成的线程不安全问题。

  • 缺点:当该类被加载的时候,会初始化该实例和静态变量并被创建并分配内存空间,并且会一直占用内存。

饱汉式

  • 优点:写起来很简单,在第一次调用的时候才会初始化,节省了内存。

  • 缺点:线程不安全,多个线程调用可能会出现多个实例。

  • 总结:书写简单,线程不安全,效率还行。

虽然 饱汉式可以通过加上synchronized关键字保证线程安全。但是效率方法来说还不说是最优。

这里在介绍下个人认为在JDK1.5之前最优的两种写法,一种是静态内部类,另一种是双重锁检查

静态内部类
定义一个私有的构造方法,定义一个该类私有静态的内部类,然后在内部类中定义一个该类的静态变量,然后通过公共的final修饰的静态方法调用返回实例。

  class  SingletonTest4 {
      private SingletonTest4(){
        }
       private static class SingletonTest5{
           private static SingletonTest4 instance = new SingletonTest4();
        }
        public static final SingletonTest4 getInstance(){
            return SingletonTest5.instance;
        }
   }
Copy after login

因为该类的内部类是私有的,除了对外公布的公共静态方法getInstance(),是无法访问的。因为它是延迟加载,所以读取读取实例的时候不会进行同步,几乎没有性能的缺陷,而且还是线程安全的,并且不依赖JDK的版本。

双重锁检查
定义一个私有构造方法,通过volatile定义静态私有变量,保证了该变量的可见性,然后定义一个共有的静态方法,第一次对该对象实例化时与否判断,不为空直接返回,提升效率;然后使用synchronized 进行同步代码块,防止对象未初始化时,在多线程访问该对象在第一次创建后,再次重复的被创建;然后第二次对该对象实例化时与否判断,如果未初始化,则初始化,否则直接返回该实例。

  class SingletonTest6 { 
        private SingletonTest6() { 
        }   
        private static volatile SingletonTest6 instance;  
        public static SingletonTest6 getIstance() { 
            if (instance == null) {
                synchronized (SingletonTest6.class) {
                    if (instance == null) {
                        instance = new SingletonTest6();   
                    }   
                }   
            }   
            return instance;   
        }   
    }
Copy after login

这种模式在很长的一段时间内可以说是最优的了,内存占用低,效率高,线程安全,多线程操作原子性。但是有个缺点就是书写麻烦,对新手不太友好。

JDK1.5之后出现了枚举,并且完美支持单例模式,并且线程安全、效率高!但是这些不是最重要的,最重要的是书写超级简单!究竟有多简单,看下面的示例应该就可以了解一下了。。。

枚举单例

 enum SingletonTest7{
        INSTANCE;
     }
Copy after login

对的,你没看错,就这点代码,其它不需要了。。。
枚举需要在JDK1.5之后的版本,它无偿提供序列化机制,绝对防止多次实例化,即使在面对复杂的序列化或者反射攻击的时候。这种方法也被Effective Java作者Josh Bloch 所提倡。

总结

单例模式的几种使用就到这了,那么我们来总结下使用单例模式需要注意什么(不包括枚举)。

  1. 构造方法私有化(private);

  2. 定义一个私有(private)静态(static)实例化对象;

  3. 对外提供一个公共(public)静态(static)的方法得到该实例;

相关推荐:

Java中Spring Boot有什么优势?

java中三目运算符和数组方法以及整数比较大小的代码

The above is the detailed content of What are Java design patterns? Introduction to Singleton Pattern in Java Design Patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template