aboutsummaryrefslogtreecommitdiff
path: root/gen_object
diff options
context:
space:
mode:
authorNat Lasseter <nat.lasseter@york.ac.uk>2024-01-22 10:23:58 +0000
committerNat Lasseter <nat.lasseter@york.ac.uk>2024-01-22 10:23:58 +0000
commita79414bcf14d17c58e040a7b8524f7bd8f7e5e03 (patch)
tree4f2f232aca568711ecb35caa3444b54f4dfa4361 /gen_object
Migrate from gists
Diffstat (limited to 'gen_object')
-rw-r--r--gen_object/a_cat.erl13
-rw-r--r--gen_object/gen_object.erl31
-rw-r--r--gen_object/test_a_cat.erl11
3 files changed, 55 insertions, 0 deletions
diff --git a/gen_object/a_cat.erl b/gen_object/a_cat.erl
new file mode 100644
index 0000000..3e3b00f
--- /dev/null
+++ b/gen_object/a_cat.erl
@@ -0,0 +1,13 @@
+% This is a cat. It behaves like a generic object.
+
+-module(a_cat).
+-behaviour(gen_object).
+-export([initialise/1, handle_message/3]).
+
+initialise([Name]) ->
+ {Name, "Meow"}.
+
+handle_message(say, [Word], {Name, Word}) ->
+ {Word, {Name, Word}};
+handle_message(say, _, State) ->
+ {"", State}.
diff --git a/gen_object/gen_object.erl b/gen_object/gen_object.erl
new file mode 100644
index 0000000..1990ec2
--- /dev/null
+++ b/gen_object/gen_object.erl
@@ -0,0 +1,31 @@
+% This is the behaviour definition for a generic object.
+
+-module(gen_object).
+-export([new/2, delete/1, send/3]).
+
+-callback initialise(Args :: [any()]) -> State :: any().
+-callback handle_message(Msg :: atom(), Args :: [any()], State :: any()) -> {Response :: any(), New_State :: any()}.
+
+send(Obj, Msg, Args) ->
+ Obj ! {self(), Msg, Args},
+ receive
+ Response ->
+ Response
+ end.
+
+new(CBM, Args) ->
+ State = apply(CBM, initialise, [Args]),
+ spawn(fun() -> loop(CBM, State) end).
+
+loop(CBM, State) ->
+ receive
+ gen_object__bif__exit ->
+ ok;
+ {From, Msg, Args} ->
+ {Resp, New_State} = apply(CBM, handle_message, [Msg, Args, State]),
+ From ! Resp,
+ loop(CBM, New_State)
+ end.
+
+delete(Obj) ->
+ Obj ! gen_object__bif__exit.
diff --git a/gen_object/test_a_cat.erl b/gen_object/test_a_cat.erl
new file mode 100644
index 0000000..589bb97
--- /dev/null
+++ b/gen_object/test_a_cat.erl
@@ -0,0 +1,11 @@
+% This is where we test the cat to make sure that it does not bark.
+
+-module(test_a_cat).
+-export([main/0]).
+
+main() ->
+ MyCat = gen_object:new(a_cat, ["Fred"]),
+ FredSays = gen_object:send(MyCat, say, ["Woof"]),
+ gen_object:delete(MyCat),
+
+ io:format("Fred says: ~p~n", [FredSays]).