zoukankan      html  css  js  c++  java
  • 单例模式的饿汉式实现

    23种模式

    单例模式:只存在一个对象实例,并且该类只提供一个取得其对象实例的方法。

                      若让他只产生一个对象,需要将类的构造方法访问权限设为private,这样就不能用new操作在类的外部产生类的对象,

                      但是在类的内部仍然可以产生该类的对象。导致该类对象的变量也必须定义成静态的。

    饿汉式:

    package com.aff.singleton;
    
    //单例模式:使得一个类只能够创建一个对象
    
    public class TestSingleton {
        public static void main(String[] args) {
            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();
            System.out.println(s1 == s2);
        }
    }
    
    // 只能创建Singleton的单个实例,饿汉式
    class Singleton {
        // 私有化构造器,在内的外部不能够调用次构造器
        private Singleton() {
        }
    
        // 在类的内部创建一个类的实例
        private static Singleton instance = new Singleton();
    
        // 私有化此对象,通过公共的方法调用
        // 此公共的方法,只能通过类来调用, 因为设置为static,同时类的实例也必须为static声明的
        public static Singleton getInstance() {
            return instance;
        }
    }
    输出结果:

    true



    All that work will definitely pay off
  • 相关阅读:
    POJ 3672 水题......
    POJ 3279 枚举?
    STL
    241. Different Ways to Add Parentheses
    282. Expression Add Operators
    169. Majority Element
    Weekly Contest 121
    927. Three Equal Parts
    910. Smallest Range II
    921. Minimum Add to Make Parentheses Valid
  • 原文地址:https://www.cnblogs.com/afangfang/p/12529909.html
Copyright © 2011-2022 走看看