赞
踩
单例模式(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); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。