erlang otp 自定义behaviour

习惯用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~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值