erlang学习:gen_server入门

学习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}

以下是代码测试截图
请添加图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值