erlang 自定义behaviour

参考文章:

关于Erlang中的behaviour

erlang 如何自定义 behaviour

behaviour 定义区别

例子中的behaviour区别

my_behaviour 自定义behaviour方式没有类型规范的约束,约束只有函数名和元数
test_behaviour 自定义behaviour方式简化了一些

源代码

-module(my_behaviour).
-export([behaviour_info/1]).
-export([start/1, stop/0]).

behaviour_info(callbacks) ->
        [ {init, 1},
         {handle, 2}];
behaviour_info(_Other) ->
        undefined.

start(Mod) ->
        State = Mod:init(0),
        {ok, State2} = Mod:handle(add, State),
        io:format("state : ~p~n", [State2]).

stop() ->
        stop.
-module(test_behaviour).
-export([start/1, stop/0]).
-callback init( number() ) -> number().
-callback handle( Event :: atom(), ARG::number() ) -> number().
start(Mod) ->
        State = Mod:init(0),
        {ok, State2} = Mod:handle(add, State),
        io:format("state : ~p~n", [State2]).

stop() ->
        stop.
-module(use_my_behaviour).
% -behaviour(my_behaviour).
-behaviour(test_behaviour).
-export([init/1, handle/2]).

init(State) ->
        io:format("init ~p~n", [State]),
        State.

handle(Request, State) ->
        io:format("handle request:~p state:~p~n", [Request, State]),
        State2 = State + 1,
        {ok, State2}.

结果

结果一:

 
   

c(my_behaviour).
{ok,my_behaviour}
5> c(use_my_behaviour).
{ok,use_my_behaviour}
6> my_behaviour:start(use_my_behaviour).
init 0
handle request:add state:0
state : 1
ok


结果二:

c(test_behaviour).
{ok,test_behaviour}
16> c(use_my_behaviour).
{ok,use_my_behaviour}
17> test_behaviour:start(use_my_behaviour).
init 0
handle request:add state:0
state : 1
ok

转载于:https://www.cnblogs.com/ShankYan/p/4198476.html

你可能感兴趣的:(erlang 自定义behaviour)