java设计模式-单例模式(Singleton)

单例模式介绍

单例模式(Singleton)就是一个类只能有一个实例,自行实例化,并向系统提供这一实例,这个类就是单例类。单例模式的特点:

  • 一个类只能有一个实例;
  • 单例类自己实例化;
  • 单例类给其它对象提供这个单一实例。

资源管理类经常被设计为单例模式,例如管理属性文件的类。

饿汉式单例模式

饿汉式就是在单例类被加载的时候就已经创建了单一实例。构造函数必须是私有的,这样外部无法调用,其它类也无法继承。

代码示例一:

package com.thb;

public class SingletonClass {

	private static SingletonClass instance = new SingletonClass();
	
	// 私有默认构造函数
	private SingletonClass() {
		
	}
	
	// 静态工厂方法
	public static SingletonClass getInstance() {
		return instance;
	}
}

代码示例二:

io.netty.channel.DefaultSelectStrategyFactory就是一个饿汉式单例类:

/*
 * Copyright 2016 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.channel;

/**
 * Factory which uses the default select strategy.
 */
public final class DefaultSelectStrategyFactory implements SelectStrategyFactory {
    public static final SelectStrategyFactory INSTANCE = new DefaultSelectStrategyFactory();

    private DefaultSelectStrategyFactory() { }

    @Override
    public SelectStrategy newSelectStrategy() {
        return DefaultSelectStrategy.INSTANCE;
    }
}

懒汉式单例模式

懒汉式是外部引用这个单例类的时候再实例化。构造函数必须是私有的,这样外部无法调用,其它类也无法继承。

代码示例(注意增加了获取实例的方法增加了同步):

package com.thb;

public class SingletonClass {

	private static SingletonClass instance = null;
	
	// 私有默认构造函数
	private SingletonClass() {
		
	}
	
	// 静态工厂方法
	public static synchronized SingletonClass getInstance() {
		if (instance == null) {
			instance = new SingletonClass();
		}
		return instance;
	}
}

登记式单例模式

登记式单例模式是为了克服懒汉式单例和饿汉式单例不能继承的问题而设计的。登记式单例的构造函数是保护的,可以被继承。

代码示例:

package com.thb;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

public class SingletonClass {
	
	private static HashMap<String, SingletonClass> regMap = new HashMap(); 
	static
	{
		SingletonClass instance = new SingletonClass();
		regMap.put(instance.getClass().getName(), instance);
	}
	
	// 保护默认构造函数
	protected SingletonClass() {
		
	}
	
	// 静态工厂方法
	public static SingletonClass getInstance(String name) {
		if (name == null) {
			name = SingletonClass.class.getName();
		}
		if (regMap.get(name) == null) {			
			try {
				regMap.put(name, (SingletonClass)Class.forName(name).getDeclaredConstructor().newInstance());
			} catch (InstantiationException e) {				
				e.printStackTrace();
			} catch (IllegalAccessException e) {				
				e.printStackTrace();
			} catch (IllegalArgumentException e) {				
				e.printStackTrace();
			} catch (InvocationTargetException e) {				
				e.printStackTrace();
			} catch (NoSuchMethodException e) {				
				e.printStackTrace();
			} catch (SecurityException e) {				
				e.printStackTrace();
			} catch (ClassNotFoundException e) {				
				e.printStackTrace();
			}				
		
		}
		return regMap.get(name);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值