设计模式:每个类创建一个对象

时间:2015-10-26 10:20:08

标签: java design-patterns

我想为每个类类型创建一个对象,例如Logger class of Apache如果您的类没有实例则创建一个新的Logger实例,否则它会为您提供一个新的。{/ p>

我在考虑这种类工厂:

public class Logger {

    private String TAG;//the class name   
    private static HashMap<String, Logger> loggerList = new HashMap<String, Logger>();

    private Logger(String className){
        TAG="["+className+"]";
    }

    public static Logger getLogger(String className){
        Logger logger= loggerList.get(className);
        if( logger != null){
            return logger;
        }else{
            logger= new Logger(className);
            loggerList.put(className, logger);
            return (logger);
        }       
    }

我不知道这是否是最好的方法。还有其他更优化的方法吗?

1 个答案:

答案 0 :(得分:0)

如何将Logger分开,以便它没有标记:

public interface Logger {
    void log(String tag, String message);
}

public enum DefaultLogger implements Logger {
    INSTANCE;
}

和Log Writer:

public class LogWriter {
    private final String tag;
    private final Logger logger;

    public LogWriter(String tag, Logger logger) {
        this.tag = tag;
        this.logger = logger;
    }

    public static forClass(Class clazz, Logger logger) {
        return new LogWriter("["+ clazz.getName() +"]", logger);
    }

    public static forClass(Class clazz) {
        return forClass(clazz, DefaultLogger.INSTANCE);
    }

    public void write(String message) {
       logger.log(tag, message);
    }
}

用法:

LogWriter log = LogWriter.forClass(A.class);
log.log("ABC");

然后你为每个实例创建一个LogWriter,因为为什么不是,它们很轻,或者如果你真的必须重用它们,就将它们存储在类中的静态中:

public class A {
    private final static LogWriter log = LogWriter.forClass(A.class);
}