抽象类中的Java Lazy Load Singleton

问题描述 投票:0回答:2

我试图用Java中的Abstract类实现Singleton Instance。我读过就像实现它一样,LazyLoad是最好的做法。我无法做到这一点,因为我对这种模式甚至Java都不太习惯。

  1. getInstance()总是为null,我不确定为什么?
  2. 我不认为这是在构造实例时延迟加载。
  3. 除此之外,任何其他评论都是受欢迎的,因为我是Java的新手,之前曾在c#上工作过。

这是我的,

接口:

public interface IConditionAppender{
    public String Append();
}

抽象

public abstract AppenderBase {

    private static IConditionAppender instance;

    protected AppenderBase(IConditionAppender instance)
    {
         this.instance = instance;
    }

    public static IConditionAppender getInstance(){ return instance; }
}

履行

public final class AndAppender extends AppenderBase implements IConditionAppender {

private AndAppender()
{
    super(new AndAppender())
}

@Override
public String Append()
{
    return " AND ";
}

}

测试

System.out.println(AndAppender.getInstance().Append());
java singleton lazy-loading
2个回答
1
投票

以下是AndAppender的实现方式

public final class AndAppender implements ConditionAppender {
    private static final AndAppender instance;
    public static AndAppender getInstance() {
        if (instance == null)
            instance = new AndAppender();
        return instance;
    }

    private AndAppender() { }

    @Override
    public String append() {
        return " AND ";
    }
}

同样的方法为OrAppender等。

注意:此实现不是线程安全的。


更简单的方法是使用Enum,默认情况下是单例,可以实现接口。

public enum  Appender implements ConditionAppender {
    AND(" AND "), OR(" OR ");

    final String operation;

    Appender(String operation) {
        this.operation = operation;
    }

    @Override
    public String append() {
        return operation;
    }

    public static void main(String[] args) {
        System.out.println(AND.append());
        System.out.println(OR.append());

    }
}

1
投票

下面的代码可以帮助你〜

public abstract class AbstractSingleton {

    private static Map<String, AbstractSingleton> registryMap = new HashMap<String, AbstractSingleton>();

    AbstractSingleton() throws SingletonException {
        String clazzName = this.getClass().getName();
        if (registryMap.containsKey(clazzName)) {
            throw new SingletonException("Cannot construct instance for class " + clazzName + ", since an instance already exists!");
        } else {
            synchronized (registryMap) {
                if (registryMap.containsKey(clazzName)) {
                    throw new SingletonException("Cannot construct instance for class " + clazzName + ", since an instance already exists!");
                } else {
                    registryMap.put(clazzName, this);
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T extends AbstractSingleton> T getInstance(final Class<T> clazz) throws InstantiationException, IllegalAccessException {
        String clazzName = clazz.getName();
        if (!registryMap.containsKey(clazzName)) {
            synchronized (registryMap) {
                if (!registryMap.containsKey(clazzName)) {
                    T instance = clazz.newInstance();
                    return instance;
                }
            }
        }
        return (T) registryMap.get(clazzName);
    }

    public static AbstractSingleton getInstance(final String clazzName)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        if (!registryMap.containsKey(clazzName)) {
            Class<? extends AbstractSingleton> clazz = Class.forName(clazzName).asSubclass(AbstractSingleton.class);
            synchronized (registryMap) {
                if (!registryMap.containsKey(clazzName)) {
                    AbstractSingleton instance = clazz.newInstance();
                    return instance;
                }
            }
        }
        return registryMap.get(clazzName);
    }

    @SuppressWarnings("unchecked")
    public static <T extends AbstractSingleton> T getInstance(final Class<T> clazz, Class<?>[] parameterTypes, Object[] initargs)
            throws SecurityException, NoSuchMethodException, IllegalArgumentException,
            InvocationTargetException, InstantiationException, IllegalAccessException {
        String clazzName = clazz.getName();
        if (!registryMap.containsKey(clazzName)) {
            synchronized (registryMap) {
                if (!registryMap.containsKey(clazzName)) {
                    Constructor<T> constructor = clazz.getConstructor(parameterTypes);
                    T instance = constructor.newInstance(initargs);
                    return instance;
                }
            }
        }
        return (T) registryMap.get(clazzName);
    }

    static class SingletonException extends Exception {
        private static final long serialVersionUID = -8633183690442262445L;

        private SingletonException(String message) {
            super(message);
        }
    }
}

来自:https://www.cnblogs.com/wang9192/p/3975748.html

© www.soinside.com 2019 - 2024. All rights reserved.