Home > Java > JavaBase > What are the design patterns in Java?

What are the design patterns in Java?

王林
Release: 2019-11-12 15:53:07
Original
2724 people have browsed it

What are the design patterns in Java?

Design patterns in Java:

Strategy pattern, proxy pattern, singleton pattern, multiple instance pattern, factory method pattern, abstract factory Pattern, facade pattern, adapter pattern, template method pattern, builder pattern, bridge pattern, command pattern, decorator pattern, iterator pattern, composition pattern, observer pattern, chain of responsibility pattern, visitor pattern, state pattern, prototype pattern, Mediator mode, interpreter mode, Hengyuan mode, memo mode.

Example:

Single case mode

The so-called singleton design means that a class only allows one instantiated object to be generated. The best understood design pattern is divided into lazy man style and hungry man style.

Hungry Chinese style: The construction method is privatized. New instantiated objects cannot be generated externally. The instantiated objects can only be obtained through static methods.

class Singleton {
    /**
     * 在类的内部可以访问私有结构,所以可以在类的内部产生实例化对象
     */
    private static Singleton instance = new Singleton();
    /**
     * private 声明构造
     */
    private Singleton() {

    }
    /**
     * 返回对象实例
     */
    public static Singleton getInstance() {
        return instance;
    }

    public void print() {
        System.out.println("Hello Singleton...");
    }
}
Copy after login

Lazy Chinese style: When using Singleton for the first time The operation of instantiating the object will only be generated when the object is created.

class Singleton {

    /**
     * 声明变量
     */
    private static volatile Singleton singleton = null;

    /**
     * 私有构造方法
     */
    private Singleton() {

    }

    /**
     * 提供对外方法
     * @return 
     */
    public static Singleton getInstance() {
        // 还未实例化
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
    public void print() {
        System.out.println("Hello World");
    }
}
Copy after login

Recommended tutorial: Java tutorial

The above is the detailed content of What are the design patterns in Java?. 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