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

    定义

    单例模式是一种对象创建型模式。GoF对单例模式的定义是:保证一个类、只有一个实例存在,同时提供能对该实例加以访
    问的全局访问方法。

    使用单例模式的原因

    • 在多个线程之间,比如servlet环境,共享同一个资源或者操作同一个对象。

    • 在整个程序空间使用全局变量,共享资源。

    • 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。

    单例模式实现

    1. 饿汉式:在单线程和多线程中均无问题。

      public class Person {
      	public static final Person person = new Person();
      	private String name;
      	
      	
      	public String getName() {
      		return name;
      	}
      
      	public void setName(String name) {
      		this.name = name;
      	}
      	
      	//构造函数私有化
      	private Person() {
      	}
      	
      	//提供一个全局的静态方法
      	public static Person getPerson() {
      		return person;
      	}
      }
      
    2. 懒汉式:多线程中不能保证唯一的对象。若在多线程中使用懒汉式,可用2.1 、2.2 方式。

       public class Person2 {
       	private String name;
       	private static Person2 person;
       	
       	public String getName() {
       		return name;
       	}
      
       	public void setName(String name) {
       		this.name = name;
       	}
       	
       	//构造函数私有化
       	private Person2() {
       	}
       	
       	//提供一个全局的静态方法
       	public static Person2 getPerson() {
       		if(person == null) {
       			person = new Person2();
       		}
       		return person;
       	}
       }
      

      2.1 添加synchronized的懒汉式

       public class Person3 {
       	private String name;
       	private static Person3 person;
       	
       	public String getName() {
       		return name;
       	}
      
       	public void setName(String name) {
       		this.name = name;
       	}
       	
       	//构造函数私有化
       	private Person3() {
       	}
       	
       	//提供一个全局的静态方法,使用同步方法
       	public static synchronized Person3 getPerson() {
       		if(person == null) {
       			person = new Person3();
       		}
       		return person;
       	}
       }
      

      2.2 双重检查

       public class Person4 {
       	private String name;
       	private static Person4 person;
       	
       	public String getName() {
       		return name;
       	}
      
       	public void setName(String name) {
       		this.name = name;
       	}
       	
       	//构造函数私有化
       	private Person4() {
       	}
       	
       	//提供一个全局的静态方法
       	public static Person4 getPerson() {
       		if(person == null) {
       			synchronized (Person4.class) {
       				if(person == null) {
       					person = new Person4();
       				}
       			}
       			
       		}
       		return person;
       	}
       }
  • 相关阅读:
    PHP新的垃圾回收机制:Zend GC详解
    SSH隧道技术简介
    mysql主从延迟
    非root配置linux下vim
    PHP 中的 9 个魔术方法
    PHP内核介绍及扩展开发指南—Extensions 的编写(下)
    PHP内核介绍及扩展开发指南—Extensions 的编写
    php 扩展开发
    php opcode
    rsa 数学推论
  • 原文地址:https://www.cnblogs.com/esileme/p/7561620.html
Copyright © 2011-2022 走看看