Factories

This commit is contained in:
Andrey Breslav
2010-11-19 12:57:12 +03:00
parent 8beb0da924
commit 1af0027ee7
2 changed files with 22 additions and 7 deletions
+2
View File
@@ -18,4 +18,6 @@ val GOD = object {
fun sendMessage(message : GodMEssage) = throw new RuntimeException(message.name) fun sendMessage(message : GodMEssage) = throw new RuntimeException(message.name)
}; };
// Groovy like syntax: too many things to assume
addMouseListener([mouseClicked : {e => doFoo()}]); addMouseListener([mouseClicked : {e => doFoo()}]);
+20 -7
View File
@@ -1,13 +1,26 @@
class ConcreteClass { class Foo(bar : Bar) {
this() {} } static {
private val cache = HashMap<Bar, Foo>()
Foo() {
return Foo(null);
}
Foo(bar : Bar) {
if (bar in cache.keys) return cache[bar]
val newFoo = this(bar) // calls the primary constructor
cahce[bar] = newFoo
return newFoo
}
} }
// Implicitly generated a factory for ConcreteClass with a no-argument factory method // To create an object of Foo
val foo = Foo()
or
val foo = Foo(Bar())
interface class IFooBarInterface { // Subclass (Foo must be marked as extendable/open, i.e. ont sealed)
new () { } class FooSub(S : String) : Foo() { // Delegates to Foo created as a result of the factory method Foo()
}
factory }