美文网首页
单利模式

单利模式

作者: 郎中_大橙子 | 来源:发表于2017-07-28 15:59 被阅读10次

    1、饿汉式

    package com.company;
    
    /**
     * 饿汉式
     * Created by dra on 2017/7/7.
     */
    public class Person {
    
    
        private String name;
    
        private static final Person PERSON = new Person();
    
        private  Person(){}
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * 获取单利
         * @return
         */
        public static Person getPerson(){
            return PERSON;
        }
    }
    

    2、懒汉式

    package com.company;
    
    /**
     * 懒汉式
     * Created by dra on 2017/7/7.
     */
    public class Person2 {
    
    
        private String name;
    
        private static Person2 person;
    
        private Person2(){}
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * 获取单利
         * @return
         */
        public static Person2 getPerson(){
            if (person == null){
                person= new Person2();
            }
    
            return person;
        }
    }
    
    

    3、双重检查

    package com.company;
    
    /**
     * 双重检查
     * Created by dra on 2017/7/7.
     */
    public class Person2 {
    
    
        private String name;
    
        private static Person2 person;
    
        private Person2(){}
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * 获取单利
         * @return
         */
        public static Person2 getPerson(){
            if (person== null){
                synchronized (Person2.class){
                    if (person== null){
                        person= new Person2();
                    }
                }
            }
            return person;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:单利模式

          本文链接:https://www.haomeiwen.com/subject/cwcrhxtx.html