%% @author ping
%% @doc @todo Add description to my_bank.
-module(my_bank).
-behaviour(gen_server).
%%-export([start/0,stop/0,new_account/1,deposit/2,withdraw/2]).
-export([start/0]).
%%回调模块
-export([init/1,handle_call/3,handle_cast/2,handle_info/2,
terminate/2,code_change/3]).
-compile(export_all).
start()->
gen_server:start_link({local,?MODULE}, ?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 =< 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(_Mag,State) -> { noreply,State }.
handle_info(_Info,State) -> { noreply,State }.
terminate(_Reason,_State) -> ok.
%%热代码替换
code_change(_OldVsn,State,Extra) -> { ok,State }.
my_bank
最新推荐文章于 2021-03-23 20:01:51 发布