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

    单例设计模式:(Singlelon)

    如果没有构造方法,会在编译时候自动构造一个什么都不干的构造方法

    如果构造方法私有化,则外部不能使用 new 关键字实例化对象。

    class Singleton{

        static Singleton instance = new Singleton() ;

        public void print(){

            System.out.println("Hello") ;

        }

    }

    public class Test{

        public static void main(String arg[]){

            Singleton s = null;

            s = Singleton.instance ;

            s.print() ;

        }

    }

    但是这样不符合类的封装性

    所以需要用 private修饰instance

    class Singleton{

        private static Singleton instance = new Singleton() ;

        public void print(){

            System.out.println("Hello") ;

        }

        public static Singleton getInstance(){

            return instance ;

        }

    }

    public class Test{

        public static void main(String arg[]){

            Singleton s = null;

            s = Singleton.getInstance() ;

            s.print() ;

        }

    }

    但是现在无论

    S1 = Singleton.getInstance();

    S2 = Singleton.getInstance();

    S3 = Singleton.getInstance();

    得到的都是同一个实例。

    如果要控制一个类的实例化个数,那么就要锁定构造方法!!!

    但是如果现在将getInstance方法中变为

    Return new Singleton();也是有点小缺陷的

    所以程序要这么写:
    class Singleton{

        private static final Singleton INSTANCE = new Singleton() ;

        public void print(){

            System.out.println("Hello") ;

        }

        public static Singleton getInstance(){

            return INSTANCE ;

        }

    }

    public class Test{

        public static void main(String arg[]){

            Singleton s = null;

            s = Singleton.getInstance() ;

            s.print() ;

        }

    }

    可是对于单例设计模式有两种模式:

    1. 饿汉式
    2. 懒汉式

    之前写的就是饿汉式,在Singleton定义的时候就准备好了一个对象,并没有关系这个对象有没有使用,懒汉式的特点是第一次使用 的时候实例化,以后都不实例化。

    懒汉式:

    class Singleton{

        private static final Singleton instance ;

        public void print(){

            System.out.println("Hello") ;

        }

        public static Singleton getInstance(){

            if(instance == null)

                return new Singleton() ;

            else

                return instance ;

        }

    }

    public class Test{

        public static void main(String arg[]){

            Singleton s = null;

            s = Singleton.getInstance() ;

            s.print() ;

        }

    }

  • 相关阅读:
    BASH让标准输出和错误输出颜色不同
    为Linux的文件管理器创建“在此打开终端”菜单
    在Linux终端中快速生成、解码二维码
    让BASH用得更舒服:提示符颜色、时间、显示返回值、终端标题显示当前目录与正在执行的命令
    Linux关联文件扩展名和打开程序
    Linux发行版教你如何选 给入门者的选择通法
    B/S架构与C/S架构的比较
    一个PB12.5安装的问题
    介绍JavaEE平台
    类与对象小结
  • 原文地址:https://www.cnblogs.com/da-peng/p/5129777.html
Copyright © 2011-2022 走看看