Creational Patterns Part 3/5: Singleton Pattern

原创 2016年05月30日 22:13:30

Creational Patterns Part 3/5: Singleton Pattern

目录


Definition

Singleton Pattern应该是设计模式中最简单的模式之一了。该模式保证一个类只会产生一个对象并且提供一个公共的接口来访问这个唯一的对象。

何时使用?当希望一个类只有一个实例时。

使用频率:Frequency of use Medium High


UML Class Diagram

Singleton Pattern


Implementation

注意使用单例模式的类的构造方法必须是私有的。

// SingletonDemo.java
package designpatterns.creationalpatterns.singleton;

public class SingletonDemo {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();

        System.out.println(s1 == s2);
    }   
}

class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

// output
true
版权声明:本文为博主原创文章,未经博主允许不得转载。

Creational Patterns Part 1/5: Factory Pattern

Creational Patterns Part 1/5: Factory Pattern目录 Creational Patterns Part 15 Factory Pattern 目录 Defin...

Creational Patterns Part 5/5: Prototype Pattern

Creational Patterns Part 5/5: Prototype Pattern目录 Creational Patterns Part 55 Prototype Pattern 目录 D...

Design Pattern - Creational Patterns - Singleton Pattern

2007 Section 1, Chapter 1 Singleton Pattern Concept The Singleton pattern is a way t...

Structural Patterns Part 3/7: Composite Pattern

Structural Patterns Part 3/6: Composite Pattern目录 Structural Patterns Part 36 Composite Pattern 目录 D...

Behavioral Patterns Part 3/11: Interpreter Pattern

Behavioral Patterns Part 3/11: Interpreter Pattern目录 Behavioral Patterns Part 311 Interpreter Patter...

Design Pattern - Creational Patterns - Factory Pattern

Section 1, Chapter 1 Factory Pattern Intr: Factories use a base class type to create a class ...

Design Pattern - Creational Patterns - Abstract Factory Pattern

2007 Section 2, Chapter 2 Abstract Factory Pattern Concept Since...

Design Pattern - Creational Patterns - Builder Pattern

2007 Section 3, Chapter 2 Builder Pattern Concept Builders usually deal with constru...

设计模式(Design Pattern) - 创建型模式(Creational Pattern) - 单例模式(Singleton Pattern) - Java实现

单例模式(Singleton Pattern):确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类成为单例类,提供全局访问的方法。实现单例模式的3个步骤: 1、private构...
  • achi010
  • achi010
  • 2017年06月25日 13:41
  • 152

Behavioral Patterns Part 2/11: Command Pattern

Behavioral Patterns Part 2/11: Command Pattern目录 Behavioral Patterns Part 211 Command Pattern 目录 Def...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Creational Patterns Part 3/5: Singleton Pattern
举报原因:
原因补充:

(最多只允许输入30个字)