zoukankan      html  css  js  c++  java
  • 单例设计模式

    单例设计模式

    具体实现

    (1)将构造方法私有化,使其不能在类的外部通过new关键字实例化该类对象。

    (2)在该类内部产生一个唯一的实例化对象,并且将其封装为private static类型。

    (3)定义一个静态方法返回这个唯一对象。

    public class testStream {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
        
        //该类只能有一个实例
        private testStream() {
        }

       //目的是为了将构造器限定为private 避免类在外部实例化
        //在同一个虚拟机范围内  单例出来的都是唯一实例 只能通过一个方向访问

        private static testStream ts1 = null;
      
        
        //这个类必须给整个系统提供这个实例对象
        public static testStream getTest() {
            if(ts1 == null) {
                ts1 = new testStream();
            }
            return ts1;
        }
    }

     测试:

    public class testMain {
        public static void main(String[] args) {
        
            //testStream s = new testStream();//构造器私有化 不能new出来
            testStream stream1 = testStream.getTest();
            
            stream1.setName("李楠");
            
            testStream stream2 = testStream.getTest();
            stream2.setName("余杰");
            
            System.out.println(stream1.getName() + "   " + stream2.getName());//输出:余杰   余杰
            
            if(stream1 == stream2) {
                System.out.println("相同的实例");//输出:相同的实例
            }
            else if(stream1 != stream2){
                System.out.println("no");
            }
        }
    }

    参考:

    https://www.cnblogs.com/binaway/p/8889184.html

    坚持学习,永远年轻,永远热泪盈眶
  • 相关阅读:
    POJ3320 Jessica's Reading Problem
    POJ3320 Jessica's Reading Problem
    CodeForces 813B The Golden Age
    CodeForces 813B The Golden Age
    An impassioned circulation of affection CodeForces
    An impassioned circulation of affection CodeForces
    Codeforces Round #444 (Div. 2) B. Cubes for Masha
    2013=7=21 进制转换
    2013=7=15
    2013=7=14
  • 原文地址:https://www.cnblogs.com/jiang0123/p/11288522.html
Copyright © 2011-2022 走看看