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

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - singleton using enum

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...