Created
August 16, 2023 10:42
-
-
Save User4574/e258a9f5e981658fcf45f29bbb34d40f to your computer and use it in GitHub Desktop.
gen_object: the start of an erlang OO behaviour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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}. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment