lundi 26 octobre 2015

Design pattern: create one object per class

I want to create one object per class type, like for example the Logger class of Apache [1] that creates a new Logger instance if there is no instance for your class otherwise it gives you a new one.

I am thinking of this kind of class factory:

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);
        }       
    }

I don't know if this is the best way to do it. Is there another way more optimised?

[1]http://ift.tt/1GsCiVC

Aucun commentaire:

Enregistrer un commentaire