This page is an archive of my old blog. Please visit DavidTucker.net for my current blog.
This site is no longer being maintained and commenting is disabled.

Getting Started with Cairngorm – Part 1

I spoke about Cairngorm 2.2 in the Flex Bootcamp at Max this week. Many people were interested in Cairngorm, but I only had about 10 minutes to explain the basics of Cairngorm. I guess the easiest way to assist these people is to do a quick blog series on the benefits of Cairngorm. This series will combine articles with "code-along" videos.

Disclaimer: I do not claim the be "the expert" on Cairngorm - I am far from it. However, I have used Cairngorm on several large projects (both at Georgia Tech and in my own business). I am certainly open to corrections if you see that I have made an error on this project. If you want "the experts" check out: Steven Webster, Alistair McLeod, Alex Uhlmann, and Peter Martin.

Note: The guys at Adobe Consulting (that developed Cairngorm) are currently investigating some new things with the framework as a whole. It is possible (actually probable) that some of these things will change in the future. One of the very specific areas of change is the Model Locator.

Part 1 – Getting Started By Using a Model Locator

The Model Locator pattern is used in Cairngorm, but you don't have to have a full Cairngorm Implementation to use the pattern. First, let's cover what benefits that you get from using a Model Locator.

A Model Locator is a centralized repository for all of the data that is needed across your application. Your data will exist inside of a "singleton class". This "class" can only have one instance of itself. Why is this important? Let me give you an example.

We have great mini-notepads at work that I use to write down data while I work. However, sometimes, I lose a notepad – get a new one, and then find the old one. After both have been heavily used – it is really hard to find out which notepad I used to write down a piece of information from one week ago. That is a simple example – but imagine if I had 20 notepads? This could get crazy.

In the same way you could have a "class" that gets "instantiated" 20 times within your application (even if you don't mean for it to). The easiest way to eliminate this problem is to use a "singleton". A singleton is a class that is never "created" in the traditional way. It has one main rule – no more than one of itself can exist at any point in time. How does it do this? I will show you in the Model Locator example.

Actionscript:
  1. package net.davidtucker.CairngormSample.model {
  2.  
  3.     import com.adobe.cairngorm.model.IModelLocator;
  4.    
  5.     [Bindable]
  6.     public class ModelLocator implements IModelLocator {
  7.        
  8.         // Single Instance of Our ModelLocator
  9.         private static var instance:ModelLocator;
  10.  
  11.         public function ModelLocator(enforcer:SingletonEnforcer) {
  12.  
  13.         if (enforcer == null) {
  14.                 throw new Error( "You Can Only Have One ModelLocator" );
  15.             }
  16.         }
  17.         
  18.         // Returns the Single Instance
  19.         public static function getInstance() : ModelLocator {
  20.                
  21.             if (instance == null) {
  22.                 instance = new ModelLocator( new SingletonEnforcer );
  23.             }
  24.             return instance;
  25.         }
  26.        
  27.         //DEFINE YOUR VARIABLES HERE       
  28.        
  29.     }
  30. }
  31.  
  32. // Utility Class to Deny Access to Constructor
  33. class SingletonEnforcer {}

This code may look a bit daunting in the beginning, but trust me that it is not as difficult as it may appear. First, we have our package definition and we import some classes. Right now we know that we will need the IModelLocator interface. To use this you will need the Cairngorm SWC that can be found here: Cairngorm. Also note - you could build a model locator without Cairngorm, and I do this frequently on small projects (you just leave out the 'implements IModelLocator' and 'import com.adobe.cairngorm.model.IModelLocator' code from the Model Locator).

Actionscript:
  1. [Bindable]
  2. public class ModelLocator implements IModelLocator {
  3.        
  4.      // Single Instance of Our ModelLocator
  5.      private static var instance:ModelLocator;

Next we have our class definition. It is important that you use the Bindable metatag directly above your class definition. This will allow all of our variables that we define inside of the Model Locator to be used for binding. We also will go ahead and create one variable. It will be called "instance" and it will be of type ModelLocator. This will be the variable where we will store our one instance of our class. It will also be denoted as a "static" property. If you are not sure what a "static" property is, it's ok - we will discuss that in our next lesson.

Actionscript:
  1. public function ModelLocator(enforcer:SingletonEnforcer) {
  2.      if (enforcer == null) {
  3.           throw new Error( "You Can Only Have One ModelLocator" );
  4.      }
  5. }

This is followed by the constructor. The constructor takes on argument - "enforcer". You will notice that this "enforcer" has a type of "SingletonEnforcer" which is defined directly after our class. Here is the logic behind that:

  • When you put a class in an Actionscript file below the main class, it is only available to that class. Many people refer to these as "utility classes" (although many people use that term in a much broader scope).
  • If the constructor requires this argument - then only our main class can create an instance of itself, because we do not have access to the "SingletonEnforcer" class - only the main class has this access.
  • We will not access our class in the normal way by using the "new" statement because we can't call the constructor (I will show you how we will do it in a bit).

Once we get inside of the constructor, we have a few lines that make sure things work as planned. The "if" statement ensures that we had a valid "enforcer" passed in. If there wasn't it throws an Error stating that "You Can Have Only One ModelLocator".

Actionscript:
  1. // Returns the Single Instance
  2. public static function getInstance() : ModelLocator {
  3.      if (instance == null) {
  4.           instance = new ModelLocator( new SingletonEnforcer );
  5.      }
  6.      return instance;
  7. }

The "getInstance" function is how we will access our ModelLocator from our application. This function simply passes back the "instance" of the class. If it doesn't exist yet, it creates it. We can now get the ModelLocator by using the following code:

Actionscript:
  1. var model:ModelLocator = ModelLocator.getInstance();

Video Example - Getting Started and Building a Contact List

Application Code
Download (418 kB)




125 Responses to “Getting Started with Cairngorm – Part 1”

  1. [...] Getting Started with Cairngorm – Part 1 [...]

  2. Now here is a clear, smart, well-paced tutorial. I have got me hooked. Thanks so much for doing all this.

  3. Hi

    Congratulations, you made a great job on these tutorials.
    I’m using Flex Builder 3.0.1 (August milestone), and I was having a little problem with the code, as a warning popped out for lack of binding in the modelLocator private variable. The solution I found as just making it Bindable, as follows:

    import net.inoventos.ContactManager.model.SampleModelLocator;
    [Bindable]
    private var modelLocator:SampleModelLocator = SampleModelLocator.getInstance();

    Please tell me if this is some change over the version of Flex Builder you used when making the tutorial.

    Thanks

  4. Ok, forget it, I see you tackled this issue in part 2 :D

  5. Fred R. says:

    David,

    Nice job on the Cairngorm tutorials. I do have a question. Why did you use an enforcer for the singleton class instead of just making the constructor private? A benefit of making the constructor private is that the compiler will be able to catch you if you try to create an instance of the class whereas in the enforcer method you don’t get any errors until runtime which is not as desirable.

    Thx,

    Fred

  6. David Tucker says:

    @Fred R. – Unlike Java, ActionScript 3 does not have private constructors. All constructors are public in AS3.

  7. Fred R. says:

    Thanks for the reply.

    I don’t understand why AS3 doesn’t support a private constructor. From a lang. design point of view I don’t see any benefit in not allowing a private constructor.

  8. Dude ,
    No doubt very best efforts to teach us important think like to dump like me ;)
    love u

  9. [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

  10. anil4it says:

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

  11. Anilkumar says:

    [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

  12. [...] Tucker :: Getting Started With Cairngorm :: Part 1 :: Part 2 :: Part 3 :: Part 4 :: Part [...]

  13. Hrishikesh says:

    Hi David,
    The tutorials are excellent, very informative and the videos are amazing.. Thanks to you, i have started implementing Cairngorm in projects in a very very short time..
    Thanks a lot and keep up the good work.

  14. valentinee214 says:

    thanks a lot :D

  15. goliath says:

    Hello, David
    i may be a bit too late with this post (and too green to question on such issues), but it seems like there is a slight difference in the way the model locator is set up in this tutorial and Webster’s Cairngorm store tutorial they host at adobe (http://www.adobe.com/devnet/flex/articles/cairngorm_pt6_03.html)

    i guess, it isn’t a good idea to paste the code here, but basically the gist is that in this tutorial you use a trick – the ‘SingletonEnforcer’. The way i understood it, is that, because it resides within the ModelLocator class, only the ModelLocator can instantiate the class (and, thus, throw it as a param to the constructor function). Thus, any ‘ var a = new ModelLocator() ‘ (be it the 1st or 10th attempt) will throw an error, because the constructor expects the SingletonEnforcer as a param, and the only way it can get one, is if it’s passed as a param via getInstance.

    The ModelLocator (Cairngorm Store) code is slightly different. The way i understand it, it you can instantiate it as ‘new ModelLocator()’/(you’re not urged to use getInstance when bringing the singleton into action), but any subsequent attempt will fail.

    What is your opinion on the issue? Maybe there are some advantages of one method over the other?

    Thanks for the tutorials O-)

  16. Chepech says:

    Thx a lot David.

    I tried to explain how Cairngorm ties in together to a team of rookie Flex developers for 2 about weeks with no significant advance.

    Then I found your material and sent them the URL. They are now rolling smoothly.

    Thanks so Much!

    If you ever come to Mexico I have a bottle of a great tequila with your name on it =)

  17. Chepech says:

    Hi goliath,

    The way David implements is based on a best practice. It is a good thing that every time you use a Singleton pattern, you make its use obvious by not using a instantiation syntax. That because its more evident to notice the use of the pattern when you see a:

    var singletonInstance:SingletonClass= SingletonClass.getInstance();

    than if you see this:

    var singletonInstance:SingletonClass = new SingletonClass();

    on the second example you have no way of knowing of the use of a Singletone unless you see the SingletonClass code.

    In Flex you need to use a SingleToneEnforcer because you cant have private constructors, that’s the only way tor prevent the user of the class form instantiating it directly.

  18. [...] Getting Started with Cairngorm – Part 1 [...]

  19. David Tucker says:

    @Chepech – Thanks! I am glad that you found the tutorials useful. I will certainly let you know the next time I head to Mexico.

  20. sandeep says:

    nice tutorial. first i am scared of this arch. you make it very easy to learn.

  21. [...]Getting Started with Cairngorm 教學系列文章 by David Tucker[...]

  22. [...] In Part 1, I discussed the basic implementation and use of the ModelLocator pattern. This pattern is one of [...]

  23. Raja says:

    Thanks for putting up the videos.

    I loved the fact that they are fast paced (and easy to understand at the same time).

    Much Appreciated!

  24. Josh G says:

    Excellent job with the tutorial. I especially liked the video. The pace was great and easy to follow.

  25. Pankaj Tiwari says:

    Excellent tutorials ! Very Informative ! Thanks a lot.

  26. Woody Chastain says:

    David,

    Many thanks for your clear instruction. I have noted in online discussions that Cairngorm is recommended for “medium to large” projects. It seems to me that MVC discipline is good even for small projects. I’ve had experiences where, due to time pressure, a small prototype just keeps growing, resulting in hard to maintain code. Why not always think and code with best possible practices? What’s your take on Cairngorm and “small” projects?

    Due to the economy my hours have been cut to 60%, and I am using the other 40% to upgrade/update my programming skills. I’ve am using many books, and your videos and source are great. I’ll get your new book, and check out the Lynda videos. and finish this Cairngorm series.

    Thanks again,
    Woody

  27. Nathan5.x says:

    Hi David,

    You really rocks dude..

    Superb and Clear explanation on Cairngorm Framework ..

    I read some article in insideria.com thats too great..

    Hope you will help when I stuck in some development on Cairngorm Framework..

    Thanks a lot dude..

  28. Anand says:

    Hi David,
    This tutorial has given the new way of designing clear front end to all developers.

    Can we have security perspective in flex with cairgorm?

    If we bypass the webservice request and directly invoking the methods then what kind of security will be at the front end? Can flex or cairngorm provide these securities …or we have to take care at backend.

  29. AjivaCat says:

    thx for your help!

  30. Kokumo says:

    David, good work.
    I can hardly find some good tutorials like you did.

    I’m trying to learn Cairngorm and i found this is the first blog that explains very clearly what “Cairngorm’s parts” does.

    Greeting from Argentina.

  31. Aarthi Sisodiya says:

    Very Interesting way to learn! Good Job!

  32. Sudhir says:

    Hello Dave,

    This tutorial really has helped get my feet wet with Flex. Thanks a ton.

    But,When I add the person names, it is not getting displayed in the contacts list. I notice it is updating the numeric part.

    Am I missing something? Please let me know.

    Thanks in advance.

  33. Sudhir says:

    I got this resolved.

  34. [...] Artigo sobre Cairngorm parte 1 e o vídeo Cairngorm Part 1 [...]

  35. Amer Dababneh says:

    Thank for this helpful tutorial.

  36. Javanes says:

    Hi; I am a Java developer, have seen lots of tutorials but I am really impressed of your style. First a teoretical article then a practical detailed video. This style should be pilot for other experts who wants to share their knowledge with beginners. Thanks a lot.

  37. [...] can exist at any point in time. How does it do this? I will show you in the Model Locator example. [...]

  38. [...] Getting Started with Cairngorm – Part 1 [...]

  39. kjv007 says:

    Thanks for this very helpful tutorial.

  40. rajeshwar says:

    Thank you so much David. It is a great place to start cairngorm. Keep up the good work.

  41. [...] David Tucker Cairngorm Tutorial Part 1 [...]

  42. I am in the middle of creating what can be described as a small application and I soon found the code all over the place.
    At first look, Caingorm put me off, it seemed beuracratic and time expensive for small projects. After your tutorial I have decided to re-write the entire application using Caingorm. I am now of the opinion that an MVC approach is essential for any project that needs data input, updating and may one day grow to something larger and your tutorials are THE best I have seen so far.
    … all applications start small …

  43. Amar Shukla says:

    Hello David,
    First of all ,Thanks a ton for making life easier with this Cairngorm series.I have one question to ask regarding this ContactList program -
    We have already made the “SampleModelLocator” as Bindable then while assigning dataProvider=”{modelLocator.people}” to the List in PeopleList.mxml it says Databinding will not be able to detect assignments to modelLocator . I am not getting the logic behind this warning.It would be a great help if you or anybody else could explain this.

  44. shreyas says:

    Hey David,

    Thank you for the wonderful tutorial on Cairngorm, really loved it.

    I’m planning to migrate over to Flash Builder in a few weeks, is there any change in the way Cairngorm is implemented for Flash Builder (syntax wise)?

    Haven’t checked out FB yet, so asking you first.

  45. hi,nice apple in your post,I love thatelegantapple,I need to find one for me,jane