Erlang OTP 自訂behaviour

來源:互聯網
上載者:User

 

為什麼要使用behaviour,如果您對erlang有所瞭解的話,就明白其中的好處。
可以做到代碼通用,可以減少錯誤,可以使用很多成熟的久經考驗的模式,可以減輕無謂的重複勞動等等。。
有些時候,你可能需要定義自己的behaviour,這可不僅僅是OTP的權力。
自己定義behaviour非常簡單,僅僅需要幾步。
下面是一個例子:

Erlang 代碼

  1. -module(my_behaviour).  
  2.   
  3. -export([behaviour_info/1]).  
  4. behaviour_info(callbacks) ->  
  5.     [{init,1},  
  6.      {handle, 2}];  
  7. behaviour_info(_Other) ->  
  8.     undefined.  
  9.   
  10. -export([start/1, stop/0]).  
  11. start(Mod) ->  
  12.     State = Mod:init(0),  
  13.     {ok, State2} = Mod:handle(add,  State),  
  14.     io:format("state :~p~n", [State2]).  
  15. stop() ->  
  16.     stop.  
-module(my_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.

上面就定義了一個名叫my_behaviour的behaviour,其需要兩個回呼函數:init/1和handle/1,以後在使用這個 behaviour時,只需要export這兩個回呼函數即可。

如:

Erlang 代碼

  1. -module(use_my_behaviour).  
  2. -behaviour(my_behaviour).  
  3. %%behaviour callback function  
  4. -export([init/1,  handle/2]).  
  5.   
  6. init(State) ->  
  7.       io:format("init ~p~n", [State]),  
  8.       State.  
  9.   
  10. handle(Request, State) ->  
  11.       io:format("handle request:~p state:~p", [Request, State]),  
  12.       State2 = State + 1,  
  13.       {ok, state2}.  
-module(use_my_behaviour).-behaviour(my_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}.

使用:

Erlang 代碼

  1. $erl  
  2. > my_behaviour:start(use_my_behaviour).  
$erl> my_behaviour:start(use_my_behaviour).

為了您的behaviour更易使用,您需要對behaviour的功用和回呼函數的參數,傳回值等進行詳細的說明。具體可以參考OTP中 gen_server等behaviour的實現。

 

 

轉載:http://clay.phpme.info/?app=article&id=1276

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.