(1)编写接口方法 start(),stop(),new_account(Who),deposit(Who,Amount),withdraw(Who,Amount)
(2)编写回调方法,我们的回调方法必须导出六个回调方法:init、1,handle_call/3,handle_cast/2,handle_info/2,terminate/2和code_change/3.
这个模板包含了一个简单的框架,可以填充它们来制作服务器。
-module(my_bank).
-behaviour(gen_server).
-export([handle_call/3,init/1,handle_info/2,terminate/2,code_change/3]).
-export([handle_cast/2,start/0,deposit/2,new_account/1,withdraw/2]).
-define(SERVER, ?MODULE).
start()->gen_server:start_link({local,?SERVER},?MODULE,[],[]).
stop()->gen_server:call(?MODULE,stop).
new_account(Who)->gen_server:call(?MODULE,{new,Who}).
deposit(Who,Amount)->gen_server:call(?MODULE,{add,Who,Amount}).
withdraw(Who,Amount)->gen_server:call(?MODULE,{remove,Who,Amount}).
init([])->{ok,ets:new(?MODULE,[])}.
handle_call({new,Who},From,Tab)->
Reply=case ets:lookup(Tab,Who) of
[] ->ets:insert(Tab,{Who,0}),
{welcome,Who};
[]->{Who,you_already_are_a_customer}
end,
{reply,Reply,Tab};
handle_call({add,Who,X},_From,Tab)->
Reply=case ets:lookup(Tab,Who) of
[] ->not_a_customer;
[{Who,Balance}]->
NewBalance=Balance+X,
ets:insert(Tab,{Who,NewBalance}),
{thanks,who,your_balance_is,NewBalance}
end,
{reply,Reply,Tab};
handle_call({remove,Who,X},_From,Tab)->
Reply=case ets:lookup(Tab,Who) of
[] ->not_a_customer;
[{Who,Balance}] when X =
NewBalance = Balance-X,
ets:insert(Tab,{Who,NewBalance}),
{thanks,who,your_balance_is,NewBalance};
[{Who,Balance}]->
{sorry,Who,you_only_have,Balance,in_the_bank}
end,
{reply,Reply,Tab};
handle_call(stop,_From,Tab)->{stop,normal,stopped,Tab}.
handle_cast(_Msg,State)->{noreply,State}.
handle_info(_Info,State)->{noreply,State}.
terminate(_Reason,_State)->ok.
code_change(_OldVsn,State,_extra)->{ok,State}
Erlang程序设计-----【瑞典】Joe Armstrong著 牛化成译—304页至308页—【M】北京:中国工信出版社和人民邮电出版社