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

      

    一、什么是单例模式

    一个类只有一个全局实例

    二、补充说明

    一般把其构造方法设为私有,另外提供一个可以获取该实例的静态方法;

    由于java存在反射机制,即使是私有构造方法,也能被外部创建,所以一般的写法严格来讲不属于单例模式;(ps:可以在构造方法内加个静态flag标志判断,保证其只能创建一次)

    违背了“单一职责原则”,该类既是工厂又是产品(自己创建了自己);

    单例模式可以改造成固定大小的多例模式;

    三、角色

    只有一个角色,就是单例;

    四、Java例子

    举几个常见的实用的例子

    1、在类加载的时候生成对象(如生成该单例对象不耗资源的情况,可以考虑使用)

    优点:线程安全;

    缺点:不能达到(单例实例在第一次被使用时构建)的效果;

    复制代码
    public class MyPrinter {
        private static  MyPrinter myPrinter = new MyPrinter();
        private MyPrinter(){
            System.out.println("implements1: created a MyPrint instance.");
        }
        public static MyPrinter getInsatnce(){
            return myPrinter;
        }
        public static void testPrint(){
            MyPrinter.getInsatnce().print("hello!");
        }
        public void print(String str){
            System.out.println(str);
        }
        
    }
    复制代码

    2、单例实例在第一次被使用时构建(单线程环境使用)

    优点:单例实例在第一次被使用时构建;

    缺点:不加锁的话,存在线程安全问题,即使加了锁,对性能也产生了影响;

    复制代码
    public class MyPrinter {
        private static  MyPrinter myPrinter = null;
        private MyPrinter(){
            System.out.println("implements2: created a MyPrint instance.");
        }
        public static synchronized MyPrinter getInsatnce(){
            if(null == myPrinter){
                myPrinter = new MyPrinter();
            }
            return myPrinter;
        }
        public static void testPrint(){
            System.out.println("hello!");
        }
        public void print(String str){
            System.out.println(str);
        }
    }
    复制代码

    3、静态内部类(推荐使用)

    优点:线程安全;单例实例在第一次被使用时构建;

    缺点:暂无发现

    复制代码
    public class MyPrinter {
    
        private static class MyPrinterHolder {
            private static MyPrinter instance = new MyPrinter();
        }
        private MyPrinter(){
            System.out.println("implements3: created a MyPrint instance.");
        }
        public static  MyPrinter getInsatnce(){
            return MyPrinterHolder.instance;
        } 
        
        public static void testPrint(){
            System.out.println("hello!");
        }
        
        public void print(String str){
            System.out.println(str);
        }
        
    }
    复制代码

    写个测试类如下,当我们没有显示的调用getInsatnce方法的时候,是不会生成单例对象的;

    复制代码
    public class Main {
        public static void main(String[] args) {
    //        MyPrinter p = MyPrinter.getInsatnce();
    //        p.print("hello world.");
            MyPrinter.testPrint();
        }
    }
    复制代码

     打印结果:

    hello!
  • 相关阅读:
    LVS与Nginx区别
    Vue报错:Vue TypeError:Cannot read property ‘xxx‘ of null
    可以这样去理解group by和聚合函数
    52条SQL语句性能优化策略
    阿里云ECS搭建Typecho博客
    Java01——入门
    一天学习一个设计模式之外观模式
    一天学习一个设计模式之组合模式
    一天学习一个设计模式之桥接模式
    一天学习一个设计模式之适配器模式
  • 原文地址:https://www.cnblogs.com/quinnsun/p/7387646.html
Copyright © 2011-2022 走看看