erlang之gen_server的例子

星期二, 2014-08-19 | Author: Lee | erlang, webgame | 2,953 views

一个简单版的gen_server的demo例子(银行存款问题了)
同时加了一个自动存钱的功能

-module(my_bank).
-behaviour(gen_server).
-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,[],[]),
			spawn(fun() -> loop() end).
 
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}).
 
autoloop_account(Who)	-> gen_server:call(?MODULE,{autoaccount,Who}).
 
init([])	-> {ok,ets:new(?MODULE,[])}.
 
handle_call({autoaccount,Who},_Form,Tab) ->
	Replay = case ets:lookup(Tab,Who) of
		[] 	-> 	ets:insert(Tab,{Who,0}),
			{welcome,Who};
		[_]	->  {Who,exsit}
	end,
	{reply,Replay,Tab};
handle_call({new,Who},_Form,Tab) ->
	Replay = case ets:lookup(Tab,Who) of
		[] 	-> 	ets:insert(Tab,{Who,0}),
				{welcome,Who};
		[_]	->	{Who,you_already_are_a_customer}
	end,
	{reply,Replay,Tab};
handle_call({add,Who,X},_Form,Tab)	->
	Replay = case ets:lookup(Tab,Who) of
		[]	->	no_a_customer;
		[{Who,Balance}]	->
			NewBalance = Balance + X,
			ets:insert(Tab,{Who,NewBalance}),
			{thanks,Who,you_balance_is,NewBalance}
		end,
	{reply,Replay,Tab};
handle_call({remove,Who,X},_Form,Tab) ->
	Replay = case ets:lookup(Tab,Who) of
		[]	->	no_a_customer;
		[{Who,Balance}]	when X=< Balance  ->
			NewBalance = Balance - X,
			ets:insert(Tab,{Who,NewBalance}),
			{thanks,Who,you_balance_is,NewBalance};
		[{Who,Balance}] ->
			{sorry,Who,you_only_have,Balance,in_the_bank}
		end,
	{reply,Replay,Tab};
 
handle_call(stop,_Form,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}.
 
loop()	->
	%io:format("loop msg start~n"),
	sleep(),
	Who = "sara",
	autoloop_account(Who),
	Nmsg = deposit(Who,100),
	io:format("now sara balance ~p~n",[Nmsg]),
	Curnum = erlang:system_info(process_count),
	io:format("process_count  ~p~n",[Curnum]),
	loop().
 
 
sleep() ->
	receive 
		after 10000 -> true
	end.

编译执行下列命令就可以看到对应的信息

Eshell > c(my_bank).  
Eshell > my_bank:start().  
Eshell > my_bank:new_account("sara").  
Eshell > my_bank:deposit("sara", 100).  
Eshell > my_bank:deposit("sara", 200).  
Eshell > my_bank:withdraw("sara", 10).  
Eshell > my_bank:withdraw("sara", 10000).  
Eshell > my_bank:stop().

Tags: ,

文章作者: Lee

本文地址: https://www.pomelolee.com/1357.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

相关文章

文章分类

Meta