单例模式

2019-04-09  本文已影响0人  蜗牛ICU

前言:

因为现在设计模式在网络上已经泛滥,但是还是有好多程序员不能够灵活的运用设计模式,这个是对设计模式简单的介绍,因为网络上比较多类似的文章,所以本人就从网络上抄了一部分,等23种设计模式整理完成之后会根据实际的需求利用设计模式在代码中设计一些开源的插件,请继续关注。

注意点:
使用时机:
场景:
优点:
使用场景:
案例:

方式一:

        public class Person {
        
            private static Person p = new Person();
        
            // 不能被实例化
            private Person() {}
            
            public static Person getInstance() {
                return  p;
            }
            
            public void sayHello() {
                System.out.println("say Hello");
            }
            
            
            public static void main(String[] args) {
                Person person = Person.getInstance();
                person.sayHello();
            }
        }
        

方式二:

public class Person2 {

    private static Person2 p;
    private Person2() {};
    
    public static Person2 getInstance() {
        if(null == p) {
            p = new Person2();
        }
        return p;
    }
}

方式三:

public class Person3 {
    private static Person3 p;
    private Person3() {};
    
    public static synchronized Person3 getInstance() {
        if(null == p) {
            p = new Person3();
        }
        return p;
    }
}

方式四:

  public class Person4 {
        private static Person4 instance = new Person4();  
        private Person4 (){}  
        
        public static Person4 getInstance() {  
           return instance;  
       }  
 }

方式五:

public class Person5 {

    private volatile static Person5 p;
    private Person5(){}
    
    public static Person5 getSingleton() {
        if(null == p) {
            synchronized (Person5.class) {  
                if(null == p ) {
                    p = new Person5();
                }
            }
        }
        return p;
    }
}

方式六:

public class Person6 {
    private static class SingletonHolder {
    private static final Person6 p = new Person6();
    }
    
    private Person6() {}
    
    public static final Person6 getInstance() {
        return SingletonHolder.p;
    }
}

方式七:

public enum Person7 {
    INSTANCE;
    public void whateverMethod() {  
    } 
}

上一篇 下一篇

猜你喜欢

热点阅读