def_interface() in object demo
[svn/Cll1h/.git] / demos / objects / objects-wiki.c
index 7d57c7042d34481ea35cfc9818dc31d85db6df84..871488b2686ecdb89dc969b607ea63e6042cb0ef 100644 (file)
@@ -1,58 +1,74 @@
-#include <cll1.h>
+#include "cll1.h"
 
 /* This is C<<1 rewrite of object polymorphism from
-   http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming */
+   http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
+   
+   Of course there are easier ways to do the same thing... :-) 
+   (G)2008 xChas */
 
-struct Animal
+def_interface(Animal,Actions)
 {
- use_interface(AnimalActions);
- char *name;
+ str method(talk) (Animal self);
 };
 
-struct AnimalActions
+def_obj(Animal)
 {
- const char *(method(talk));
-}
+ interface(Actions);
+ char *name;
+};
 
-struct *Animal get_animal(char *name, struct AnimalActions *interface)
+construct(Animal,Actions) (Animal self, str name)
 {
- struct *Animal animal=get_object(Animal,interface);
- animal->name=name;
- return animal;
+ self->name = name;
+ return self;
 }
 
-const char *cat_talk(void *_self)
+/* implementation of methods */
+
+str catTalk(Animal self)
 {
  return "Meow!";
 }
 
-const char *dog_talk(void *_self)
+str dogTalk(Animal self)
 {
  return "Arf! Arf!";
 }
 
-interface_implementation(CatActions,AnimalActions)
+/* registration of methods to object interface */
+
+Actions catActions(void)
 {
- bind_method(talk,cat_talk);
+ Get_mem(this, Actions);
+
+ this->talk = catTalk;
+ return this;
 }
 
-interface_implementation(DogActions,AnimalActions)
+Actions dogActions(void)
 {
- bind_method(talk,dog_talk);
+ Get_mem(this, Actions);
+
+ this->talk = dogTalk;
+ return this;
 }
 
+/* usage of objects inside C<<1 program */
+
 program
 {
  int i;
- struct Animals *animal[3];
- struct AnimalActions *cat = get_interface(CatActions);
- struct AnimalActions *dog = get_interface(DogActions);
-
- animal[0]=get_animal("Missy",cat);
- animal[0]=get_animal("Mr. Bojangles",cat);
- animal[0]=get_animal("Lassie",dog);
- for_range(i,0,2)
-  printf("%s: %s\n",animal[i].name,(_(animal[i],talk)));
+ Animal animal[3];
+ Actions cat = catActions();
+ Actions dog = dogActions();
+
+ animal[0] = get_obj(Animal, cat, "Missy");
+ animal[1] = get_obj(Animal, cat, "Mr. Bojangles");
+ animal[2] = get_obj(Animal, dog, "Lassie");
+
+ for_range(i, 0, 2)
+ {
+  print(animal[i]->name, ":", _(talk, animal[i]));
+ }
 
 }
This page took 0.153412 seconds and 4 git commands to generate.