Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I read a lot on stackoverflow regarding the creation of singleton classes using enum. I must have missed something because i can't reach the INSTANCE anywhere.

this is my code:

public class UserActivity {

    private DataSource _dataSource;
    private JdbcTemplate _jdbcTemplate;

    static enum Singleton {
        INSTANCE;

        private static final UserActivity singleton = new UserActivity();

        public UserActivity getSingleton() {
            return singleton;
        }
    }

    public UserActivity() {
        this._dataSource = MysqlDb.getInstance().getDataSource();
        this._jdbcTemplate = new JdbcTemplate(this._dataSource);
    }

    public void dostuff() {
     ...
    }
}

and outside I'm trying to do

UserActivity.INSTANCE.getSingleton()

or

UserActivity.Singleton.

but eclipse's code completion doesn't find anything

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

The trick is to make the enum itself the singleton. Try this:

public enum UserActivity {
    INSTANCE;

    private DataSource _dataSource;
    private JdbcTemplate _jdbcTemplate;

    private UserActivity() {
        this._dataSource = MysqlDb.getInstance().getDataSource();
        this._jdbcTemplate = new JdbcTemplate(this._dataSource);
    }

    public void dostuff() {
     ...
    }
}

// use it as ...
UserActivity.INSTANCE.doStuff();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...