Welcome to TRiBot Forums

Register now to gain access to all of our features. Once registered and logged in, you will be able to contribute to this site by submitting your own content or replying to existing content. You'll be able to customize your profile, receive reputation points as a reward for submitting content, while also communicating with other members via your own private inbox, plus much more! This message will be removed once you have signed in.

Sign in to follow this  
Followers 0
RedHawkLuffy

[Tutorial] Singleton Pattern

1 post in this topic

Hi, I'm just posting this tutorial for people who want to structure their application in a cleaner more environmentally friendly way.

A lot of people tend to static variables which is not terrible but if it can be avoided, it should be also I've seen some code that creates a new object for every class when they only need one instance of it which the Singleton Pattern takes care of.

The singleton pattern restricts instantiation of a class to ONE object. This is useful if you need to use an object in every one of your classes like a Variables object but don't want to keep creating a new object every time.

It's fairly simple to implement.

http://pastebin.com/mukKN5pJ

It basically takes advantage of a private constructor. So to create an object it has to be done inside the class which is done by the method getInstance(); Also it is synchronized and therefore thread-safe of course.

To get the instance simply call

Singleton singleton = Singleton.getInstance();

On the first call it will instantiate the object, and every other call it will simply return the instance that was already instantiated.

For more info: https://en.wikipedia.org/wiki/Singleton_pattern

The wikipedia page shows different ways you can implement the singleton pattern.

 

1 person likes this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Recently Browsing   0 members

    No registered users viewing this page.