aboutsummaryrefslogtreecommitdiff
path: root/gen_object/gen_object.erl
blob: 1990ec2e46128c913e873260ee01a5f76700eb24 (plain)
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
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.