zoukankan      html  css  js  c++  java
  • 黑马程序员面向对象06天5(单例设计模式)

    package java06;
    
    /*
     * 设计模式:解决某一类问题最行之有效的方法。
     * java中23种设计模式:
     * 单例设计模式:解决一个类在内存只存在一个对象。
     * 想要保证对象唯一。
     * 1,为了避免其他程序过多建立该类对象。先禁止其他程序建立该类对象
     * 2,还为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象。
     * 3,为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式。
     * 这三部怎么用代码体现呢?
     * 1,将构造函数私有化。
     * 2,在类中创建一个本类对象。
     * 3,提供一个方法可以获取到该对象。
     */
    class Single {
        public static Single single = null;
    
        private Single() {
        }
    
        public static Single getSingle() {
            if (single == null) {
                single = new Single();
            }
            return single;
        }
    }
    
    public class SingleDemo {
        public static void main(String[] args) {
            Single s1 = Single.getSingle();
            Single s2 = Single.getSingle();
            System.out.println(s1 == s2);//true
            Student p1 = new Student();
            Student p2 = new Student();
            System.out.println(p1 == p2);//false
        }
    }
    class Student{
          
    }
  • 相关阅读:
    Merge Sorted Array
    Remove Duplicates from Sorted List
    Integer to Roman
    String to Integer (atoi)
    Valid Parentheses
    3Sum
    Remove Duplicates from Sorted Array
    Swap Nodes in Pairs
    得到一个Object的属性
    在WebGrid中做 批量删除操作
  • 原文地址:https://www.cnblogs.com/guwenren/p/2985047.html
Copyright © 2011-2022 走看看