• 单例模式--延时初始化


    单例模式特点:构造函数声明为private,对象获取通过函数调用。

    基本单例模式(饿汉模式):

    final class Singleton{
    private static Singleton s=new Singleton(47);
    private int i;
    private Singleton(int x){i=x;}

    public static Singleton getReference(){
    return s;
    }
    public int getValue(){return i;}
    public void setValue(int x){i=x;}
    }

    静态延时初始化(懒汉模式):
    final class StaticSingleton{
    private static StaticSingleton s;
    private int i;
    private StaticSingleton(int x){i=x;}

    public static StaticSingleton getReference(){
    if(s == null){
    s=new StaticSingleton(47);
    }
    return s;
    }

    public int getValue(){return i;}
    public void setValue(int x){i=x;}
    }
    类加载延时初始化:
    final class InnerSingleton{
    private static InnerSingleton s;
    private int i;
    private InnerSingleton(int x){i=x;}

    private static class SingletonHolder{
    static InnerSingleton instance =new InnerSingleton(47);
    }
    public static InnerSingleton getReference(){
    return SingletonHolder.instance;
    }

    public int getValue(){return i;}
    public void setValue(int x){i=x;}
    }
    查找注册方式:
    接口:
    public interface EmployeeManagement {
    static String name="";
    public void setName(String name);
    }
    单例模式类:
    final class Employee implements EmployeeManagement{
    static String name;
    private static Map<String,Employee> map = new HashMap<String,Employee>();
    static{
    Employee single = new Employee();
    map.put(single.getClass().getName(), single);
    }
    public void setName(String name){
    this.name=name;
    }
    protected Employee(){}
    protected Employee(String name){this.setName(name);}
    public static Employee getInstance(String name) {
    if(name == null) {
    name = Employee.class.getName();
    System.out.println("name == null"+"--->name="+name);
    }
    if(map.get(name) == null) {
    if(map.get(name) == null) {
    try {
    map.put(name, (Employee) Class.forName(name).newInstance());
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }
    }
    return map.get(name);
    }

    public void getInfo(){
    System.out.println(name+" is here .");
    }
    }
    应用实例:
    public class RegistryService {

    public static void main(String[] args) {
    Employee em=Employee.getInstance("singleton.Employee");
    em.setName("SuYU");
    em.getInfo();
    }
    }
    资源:
    https://share.weiyun.com/5kLvDQS
    https://share.weiyun.com/5LRwSxS
  • 相关阅读:
    C# 缓存介绍与演示(转)
    sql server 2005中表的数据与excel互相导入导出的方法
    java.exe,javac.exe,javaw.exe,jar,javadoc 区别
    C# 装箱和拆箱、理论概念(非原创)
    Maven概述(非原创)
    理解java String(非原创)
    JVM JRE JDK区别于联系(非原创)
    LINQ to SQL与LINQ to Entities场景之对照(非原创)
    J2EE系统开发环境配置
    ASP.NET MVC 拦截器(转)
  • 原文地址:https://www.cnblogs.com/ssMellon/p/6414810.html
Copyright © 2020-2023  润新知