Using the Decorator Pattern with Android

The decorator pattern is a great design pattern enabling developers to add additional behaviour to a particular object. Below is a UML Diagram (from Wikipedia) showing the design pattern. To start, you have a interface that specifies all the methods that you wish to be able to extend. Then you have the concrete component or base class. This is the original class that will be running. The decorators then contain the additional logic that you wish to add the to base object. In this guide, we look at how we can do this at runtime.

UML Diagram of the Decorator Pattern

Decorator Pattern in UML, Wikipedia

 

Using this pattern, we can enable runtime behavioural variations of classes within an Android application by adding and removing decorators from the decorator stack. One problem with Android (and probably other frameworks), this pattern makes use of Object-Oriented concepts like object construction. On Android, many of the essential classes you work with e.g. Activities and Services, you have no control or ability to construct these objects. Other problems can be attributed to the fact that you do not have real (if I am wrong, then it probably is not the recommended way) control of the activity in terms of updating its reference to another (needed for decorator methods to be invoked). In other languages like C++ it is possible to do pointer manipulation, and therefore get around this problem, but in Java, you can’t.

While this method may not be ideal or perfect, it is a workaround that I am using. With that in mind lets have a look at my example code.

Interface

Firstly, we have the interface MainActivityInterface. In this class we have a single method signature pushMeClick(View V); . This method corresponds to the touch event for the button named “Push Me” (Not very imaginative I know, but you get the point).

Activity

Next, we have the core Activity MainActivity, and this class obviously extends Activity, but also implements MainActivityInterface. Within this class we have decorator class MainActivityDecorator member named toplevel. This reference is needed to direct an invocation to the top of the decorator stack. Also we have a TextView object named txtMe, used to show a piece of text in the Window. In the OnCreate(Bundle) method we get the TextView object from the View.

The method pushMeClick(View v) as declared in the interface checks to see if the class is decorated, if it is not, then a core version of that method is invoked (the base behaviour). If the class is decorated, then the decorator version of that method is invoked. We also have a method named toggleClick(View v). When the button named “ToggleDecorator” is clicked, it checks if it the activity has been decorated. If it hasn’t, then the first decorator is added to the stack. If it has been decorated once, then the second is added to the stack. And if the second has been added, it is removed, leaving only the first.

MainActivityDecorator

Next we the add the base decorator class named MainActivityDecorator. In this class we add the base activity MainActivity naming it activity (I know, I really do pick great names). We also add another class member, of the type MainActivityInterface named parent. This member is used in a decorator chain that is more than 1, with the parent object pointing to the next decorator in the chain/stack. In the decorator we have two constructors whereby the activity is used as a parameter and in one of the constructors allow for the parent decorator to be added.

Next we have the method pushMeClick(View v), to which if there is a parent decorator, the parents version of the method is invoked, if there is no parent, the core version in the base activity MainActivity is invoked. Normally in the decorator pattern you do not need this, can just run the super version. But if you do in this, you will get caught up in a recursive loop and cause a Stack Overflow. The reason this is different, is because like we said before, we can’t update the reference of an activity, and therefore the base activity has to handle the method call at first.

We also add a method to the decorator called removeSelf(). This method removes the reference to the activity (to help cut any ties that will not allow it being collected by gc), and return the decorators parent (so the activity updates its toplevel decorator reference).

Each Specific Decorator
Next we add specific decorators which extend MainActivityDecorator, and in example we just call them MainActivity_decorator_one and MainActivity_decorator_two for simplicity. In these classes I have to add a constructor which just calls its super version. I then add a pushMeClick(View v) method in each. In these methods I firstly call the super version first, I then get the TextView from the activity (package protected) and append either “, decorator1” or “, decorator2”.

 

Screenshots:

Obviously, because of the extra instructions needed, this pattern is not computationally free. When I have time, I will try and profile the effect, and update this entry with its effect

You can find this code at https://deansserver.co.uk/gitweb/?p=codeExamples/AndroidDecorator.git;a=summary where you can view and download (click on snapshot on which revision you want).

Enjoy all.

iPhone Game – LyricalGenius

Months ago I spoke briefly about a new iPhone/iPod touch game that I was starting to develop for Mammoth Graphics, well recently (a week or so ago) the work was finished, but I hadn’t had time to really sit down and blog about it. The game is called LyricalGenius and is a game targeted at people that want a general quiz game about song lyrics. Obviously the aim of the game is that for each level there is a target of correct answers the player needs to get, and if you get too many wrong, then tough luck! Development of this game has really enabled me to build on my experiences with the development of the Tour de France application which I blogged about summer last year.

The game is now in the hands of mammoth, who are in the process of final testing and adding more questions (as song lyrics need approval from Sony Records) and hopefully will see it up on app store very soon, so if you fancy a new game, give it ago!

Dev8D 2010

Last month I attended for the second year running the JISC supported Dev8D event in central London. For this year because of my change to a PhD, I had a bit more freedom to when I could attend so I decided to go two days this year instead of just one, concentrating on Thursday and Friday. What I found amazing, was how much the event had grown since last year! I’ve haven’t seen so many people like myself in ages, was really nice.

On Thursday I chose to attend the expert lighting talks in the morning with the Cloud Workshop in the afternoon.

Picture of Cloud Computing Workshop at Dev 8 D 2010

Cloud Computing Workshop

In the exper talks there a few talks in particular that stood out to me, firstly the talk about genetic programming, secondly the talk about web security which I took notice of some of the tips they suggested!

Arduino Workshops – Friday

These workshops were by far the coolest thing I’ve done in a good while! I attended two workshops, one for beginners in the morning and a more advanced workshop for the afternoon. In the morning we got a talk about the hardware and how to do very basic programs like getting a single LED to flash and also using a speaker to make very sounds, with one group able to program their arduino to make the Simpsons theme song!

Below are some of the things I worked on in the advanced workshop, including multiplexing LEDs and driving a motor using the arduino

Overall I had a great time, and look forward to next year. Hoping there to be more Arduino workshops.

Elgg development and other activities

Hey guys, only got a few more weeks of Elgg development at least for the foreseeable future anyhow, to which to I have mixed feelings about. Seems like everytime you begin to get used to and fully in your stride with something its time to change, which is a shame but equally help keeps my work and life interesting.

As of what I’ve been working on, erm.. Well I’ve been continuing with the work on the videos plugin, which for the moment is almost ahead of previous expectations. Currently I have videos uploading and being able to be played, sound’s simple but it’s not quite. I’m in the process of being able to link the videos with the opportunities on the site, but need to be told how they are to be match, or I may just implement some sort of assumption. Also been working on some cool stuff with a piece of software called GATE (General Architecture for Text Engineering), which is intending on being used to ‘mine’ the text and help find offensive words/phrases. I have been working with a fellow colleague Dr. Ying Zhang, who is in the field of text/data mining to help set up GATE for our particular context, which is now working (at least for the moment).

A very small program has been written to use the backend of the software, getting strings of text that will eventually be sent from Elgg. I’m hoping to integrate it all from this Monday, with some re-engineering of how Elgg deals with any type of entered text, sending everything to GATE first for checking, if something isn’t allowed an error message will be sent to the user. Other than that I have to try and prepare Elgg to be able to integrate with BT’s MOSAIC, which I’m unsure of my ability to complete that in time. After the project, if I have time I am planning to try and generalise the video plugin so it will work with other Elgg installations and release it on the Elgg Development site under GPL open source licence.

From December I’m then starting the iPhone game with Mammoth Graphics at Ealing Studios, which I’m actually getting quite excited about. I hope the guys have started preparing the material that I need to get started and hopefully will have a version of the game implemented for February. I just have concerns about my pay as I’m having to come off general payroll and go back to hourly slips (which is really annoying). As long as I’m not being paid less than I will be getting from my PhD bursary then I don’t mind, as I guess an agreement has been made for me to spend time on my PhD during this project giving me almost an extra 2 months for it.

At home, I’ve been working on a little project of my own. I have a lot of music and when I go to music stores I’ve found several times I can’t remember if I have a CD already. So to solve this problem I am developing two applications:

  1. A backend file crawler, that trails through my music library and automatically indexes the artist, album and songs in a database, for which a PHP set of APi’s are being written to search and retrieve this data and relay it using XML.
  2. Because I have an Android based smart phone, I’m developing a app to get these details and help facilitate easy searching of what media I have already.

The backend app is already beginning to work, though have run into a few issues already that I will need to look into. The first issue being the speed, perhaps the speed of the crawler is going to be slower as I am not testing on the machine that will be run on and the crawling is being done over a network. Other reason I think is that I need to turn it into a threaded app, and allow more songs to be sorted concurrently. This will be something I implement last as to me efficiency and speed is something you look to once everything is working. The second issue is how to deal with multiple combinations of artists, as some song aren’t made with only one artist, leaving you will potentially copies of artists and combinations of artist which may affect search results if you only type in the one of the artists. This something I will need to look into more as this project progresses. Hopefully once the backend is complete (or as complete as I feel is necessary) work on the android app will commence which I look forward to completing as the app I think will be useful by myself and my step dad as we both have the same phone.

Anyhow, until next time chums

Current Activities – Opportunity matching and mammoths

Hey guys! Been quite busy lately with this and that. Currently as you know I’ve been working with Mobsventures on their Slenky branded social networking system. This has been going better than it was, partly because of my learning curve with Elgg has excellerated lately.

Anyhow I’ve been working on opportunity matching on the platform that I’m now just polishing up for a littel demo and presentation I have to make this Tuesday for the client. I’m currently wuite happy with whats been implemented but like I said there are some parts that need polishing before I’ll be happy to display it to anyone other than my superior. Currently I have implemented different types of users (Client, User and Admin) which obviously have different functionality. The Client can add opportunties which can be diactivated and activated (not shown and shown). This opportunties can then are shown in the “All Opportunities” section for the user. The user can then choose to add these opportunities to their favourites for easy retrieval.

The nifty thing I think is that I created a kinda “smart” search. This gets all opportunities and matches based on the following in the following order:

  1. Same borough and on a category found in a favourite.
  2. Same borough.
  3. Category found in a favourite.

Tomorrow I’m hoping add a category hierachy system for the admin to control the different pre defined categories. Previding this can be done I’ll be ready for the presentation on Tuesday. If not, Monday night will be a very long one.

Laters.

“On ya Bike” – Tour De France iPhone App

Hey Guys, good time now to say that the iPhone app i have been working on is a Tour De France app. This app now is in the final stages of development before uploading to app store this monday.
The main features of this app is contain information about the stages, including detail map images, profile images to show the contours of the stage, have fly through videos of the stage and to contain information about the different climbs and sprints.
Information about the teams including the riders in the teams is included. A history section is included in the app to show all winners of the Tour De France since the first race in 1903.
In addition to this, you will be able to keep track of the overall standings of the race, which categorises the results in to:

  • Individual (Yellow Jersey)
  • Points (Green Jersey)
  • Team
  • Climber (Red Pokadot Jersey)
  • Youth (White Jersey)

I will be putting up screen shots of the app on sunday when hopefully its complete (or near). I have been working with Mammoth Graphics to complete this app. The app i think will be on app store for free, so any tour de france fans should give the app a try and hope to give a good user experience for such an amazing race!

Anyhow, going for now but screen shots will be up soon!

Laters

Viva la France!

Hey Guys! Sorry for the extreme length of time since my last post, to say I have been slightly busy would be a complete understatement! Since my last post I attended a paper workshop in Windsor for colleagues on our project to meet, discuss the current dissemination strategy and overall try and start some paper writing. This session proved to be extremely productive, but since has gone rather flat, well at least that’s my opinion. Since then I have been starting a new project for a client involving an iPhone Application development. This development has now commenced and has a deadline, at least for the iPhone development side in the next 4-5 weeks. Overall feel slightly concerned, mainly that I am the lead programmer for this (which I feel is slightly crazy for such a tight schedule). I’m slowly getting the hang of Apple iPhone development, though inexperience in using Interface Builder is causing me some head ache. Hopefully this weekend will prove productive and lower some stress I have currently. Until next time people!