Welcome to the world of Enspiral. We are an international collective of people pooling resources and ideas together to help build a better world. A social innovations incubator and resource for changemakers.

Design Patterns Are Your Friend

So you have started writing applications for mobile, a noble cause.  Unfortunately mobile is such a fast paced landscape with typically very very short deadlines.  Not deterred, good for you! On the plus side mobile is getting very busy.

Right now let’s start looking at programming tricks that will make your life easier.  You have probably come across a few already. Yet haven’t really put stock into how powerfully particular tricks, or in programming lingo ‘patterns’, are and how generally you can take advantage of them.  For example iOS uses heavily the concept of Delegates, but Delegates is a general pattern you can use anywhere.  You will have come across Delegate as a method of receiving messages/responses from various elements like views controls.

There are many Design Patterns that can make your life easier as a programmer.  We will look quickly at just one, a fairly simple one, but a good one none the less to add to your bag of tricks.

Here we go, our pattern for today is called the Singleton.

Strange name, a little, but it is descriptive of it’s function. The singleton is a way of ensuring you only have one copy of content, and that you are always operating on the same copy.

When would I want to do that,  you ask?  Well a great example is app settings.  Generally you want just one collection of settings, and you want to be able to access them anywhere.  You want to know you are reading or writing to the same copy at all times.

Cool how do I do that? Best idea is to Google ‘Singleton’ and your OS, and find an example implementation that is well used.  Things can get a little complicated when dealing with threads, so make sure you grab a thread safe example.

A rudimentary Android Settings class could look like:

Settings Class

In simple terms the core magic is the method getInstance, and the ‘static’ qualifier for _instance.  When you call the method getInstance you are returned the one and only copy of the settings class.  This means anytime you call this method, from anywhere you get the same ‘global’ object handle back.
Calling Code

And the result…

logcat


08-17 11:27:55.214: DEBUG/TestApp(315): Account Settings Now: ACCOUNT_3

Just as expected, pretty simple… but now you have a way of keeping things in one place, and accessing them when you want.


Speak Your Mind

*