习惯用oop的思想,来到otp模式,会用旧方式去思考~
而对otp设计模式渐渐有了点感觉~
记一段代码,告诉自己要用新的思考方式。
-module(dp_behaviour).
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{init,1},
{handle, 2}];
behaviour_info(_Other) ->
undefined.
-export([start/1, stop/0]).
start(Mod) ->
State = Mod:init(0),
{ok, State2} = Mod:handle(add, State),
io:format("state :~p~n", [State2]).
stop() ->
stop.
上面就定义了一个名叫dp_behaviour的behaviour,其需要两个回调函数:init/1和handle/1,以后在使用这个behaviour时,只需要export这两个回调函数即可。
-module(use_dp_behaviour).
-behaviour(dp_behaviour).
%%behaviour callback function
-export([init/1, handle/2]).
init(State) ->
io:format("init ~p~n", [State]),
State.
handle(Request, State) ->
io:format("handle request:~p state:~p", [Request, State]),
State2 = State + 1,
{ok, state2}.
调用时候:
dp_behaviour:start(use_dp_behaviour).
by dp~~~