From a79414bcf14d17c58e040a7b8524f7bd8f7e5e03 Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Mon, 22 Jan 2024 10:23:58 +0000 Subject: Migrate from gists --- gen_object/gen_object.erl | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 gen_object/gen_object.erl (limited to 'gen_object/gen_object.erl') 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. -- cgit v1.2.1