Tuesday Dec 18, 2007

Patterns in Java & JavaFX Script

One of the thoughts that I had the other day was related to design patterns in JavaFX Script. Patterns are quite popular with developers. The are books on this topic and lots of web resources. The question is how could write, for instance a Singleton, in JavaFX Script.
 
In Java it would look like this:

public class OnlyOne {

    private static OnlyOne singleton = null;

    private OnlyOne() {

    }

    public static synchronized OnlyOne getInstance() {
        if (singleton == null) {
            singleton = new OnlyOne();
        }

        return singleton;
    }
}

/\*\*
\* Test program to prove we've coded the singleton correctly
\*/
public class Driver {

    public static void main(String[] args) {
        // one would try this OnlyOne one = new OnlyOne();
        // and it won't work due to the private constructor
       
        // get an instance
        OnlyOne one = OnlyOne.getInstance();
        System.out.println("Myfirst attempt: " + one.toString());
       
        // get another instance to see if they are the same
        OnlyOne two = OnlyOne.getInstance();
        System.out.println("My second attempt: " + two.toString());
    }
}

The result of running the Driver program is: 

Myfirst attempt: onlyone.OnlyOne@9b49e6
My second attempt: onlyone.OnlyOne@9b49e6

As expected, any time one is trying to get a handle to the OnlyOne object, the same instance is returned.

About

octav

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today