学习erlang中gen_client回调模块使用
今日学习编写接口方法与回调方法
-module(my_bank).
-define(SERVER, ?MODULE).
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,
terminate/2,code_change/3,test/0,start_link/0,stop/0,new_account/1,withdraw/2,deposit/2]).
%%接口方法
start() -> gen_server:start_link({local, ?SERVER},?MODULE, [], []). %%启动一个本地服务器,第二个参数为回调模块名
stop() -> gen_server:call(?MODULE,stop). %%关闭服务器
new_account(Who) -> gen_server:call(?MODULE,{new,Who}). %%gen_server对服务器进行远程过程调用
deposit(Who, Amount) -> gen_server:call(?MODULE,{add,Who,Amount}).
withdraw(Who, Amount) -> gen_server:call(?MODULE,{remove,Who,Amount}).
%%回调方法
start_link() -> gen_server:start_link({local, ?SERVER},?MODULE, [], []).
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 =< Balance ->
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}.
%%测试用例
test() ->
start(),
%% deposit("111",100).
%%not_a_customer
%% new_account("111").
%%{welcome,"111"}
%% deposit("111",100).
%%{thanks,"111",your_balance_is,100}
%% deposit("111",200).
%%{thanks,"111",your_balance_is,300}
%% withdraw("111",10).
%%{thanks,"111",your_balance_is,290}
withdraw("111",1000).
%%{sorry,"111",you_only_have,290,in_the_bank}
以下是代码测试截图