사용자 지정 OTP 동작
OTP 동작의 구조와 공통 패턴을 캡슐화하는 사용자 지정 일반 동작을 만드는 방법을 이해합니다.
사용자 지정 OTP 동작은(는) CoddyKit의 무료 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro: What are OTP Behaviors?
You've learned about OTP behaviors like GenServer and GenStatem. They provide a standard way to build robust, fault-tolerant components.
But what if you have a recurring pattern that isn't perfectly covered by existing behaviors? This is where custom OTP behaviors come in handy!
They let you define your own generic component structure.
Why Custom Behaviors?
Creating custom behaviors offers several key advantages:
- Code Reuse: Encapsulate common logic once and reuse it across many modules.
- Consistency: Ensure all components following your behavior adhere to a specific interface and structure.
- Abstraction: Hide complex internal details, exposing a simpler API to users.
- Maintainability: Changes to the core logic only need to happen in one place.
Anatomy of a Behavior
An OTP behavior typically consists of two main parts:
- The Behavior Module: This module defines the public interface (functions users call) and often provides helper functions for the callback module. It uses the
-behaviour(gen_server)or similar attribute to link to a generic server. - The Callback Module: This is where the actual logic lives. It implements the callback functions (like
init/1,handle_call/3) required by the behavior module.
Think of it as a contract between the two.
Behavior Module: Interface
The "behavior module" is what other modules -behaviour(...) against. For custom behaviors, you'll often define a module that wraps an existing generic behavior (like gen_server) but adds your specific API.
It acts as the client-side interface for users of your custom behavior.
Key aspects:
- Defines the public functions (e.g.,
start_link/0,my_action/1). - These functions typically call
gen_server:start_link/3orgen_server:call/2internally. - It specifies the callback module using the
-callbackattribute.
Callback Module: Logic
The "callback module" is where the core functionality of your custom behavior resides. It's the module that actually implements the required functions defined by the underlying generic behavior (like gen_server or gen_statem).
- It must implement functions like
init/1,handle_call/3,handle_cast/2, etc. - These functions manage the state and respond to messages.
- This module is what the behavior module (e.g.,
gen_server) calls directly.
Counter Behavior: Start
Let's create a simple custom counter behavior. We'll wrap a gen_server to manage an integer count.
First, define the behavior module, which acts as the client API and starts the underlying gen_server.
-module(my_counter).
-behaviour(gen_server). % We wrap gen_server
-export([start_link/0, get_count/0, increment/0, decrement/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
% Public API for starting the counter
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
% --- gen_server callbacks (for *this* module acting as callback) ---
% This is where the initial state is set
init([]) ->
{ok, 0}. % Initial count is 0Counter Behavior: Functions
Now, let's add the public functions to interact with our counter (increment, decrement, get_count) and implement their corresponding handle_call logic.
These public functions will use gen_server:call/2 to send requests to the actual counter process.
-module(my_counter).
-behaviour(gen_server).
-export([start_link/0, get_count/0, increment/0, decrement/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
% Public API for interacting with the counter
get_count() ->
gen_server:call(?MODULE, get_count).
increment() ->
gen_server:call(?MODULE, increment).
drcrement() ->
gen_server:call(?MODULE, decrement).
% --- gen_server callbacks ---
init([]) ->
{ok, 0}.
handle_call(get_count, _From, State) ->
{reply, State, State};
handle_call(increment, _From, State) ->
NewState = State + 1,
{reply, NewState, NewState};
handle_call(decrement, _From, State) ->
NewState = State - 1,
{reply, NewState, NewState};
handle_call(_Request, _From, State) ->
{reply, {error, unknown_request}, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.Using the Custom Counter
With our my_counter behavior defined, we can now easily use it from an Erlang shell or another module. Notice how simple the client-side code is!
You don't need to know the gen_server details; you just use the custom behavior's API.
-module(counter_app).
-export([run/0]).
run() ->
% Start our custom counter behavior
io:format("Starting counter...~n"),
my_counter:start_link(),
io:format("Current count: ~p~n", [my_counter:get_count()]),
io:format("Incrementing...~n"),
my_counter:increment(),
io:format("Current count: ~p~n", [my_counter:get_count()]),
io:format("Decrementing...~n"),
my_counter:decrement(),
io:format("Current count: ~p~n", [my_counter:get_count()]),
% Stop the counter (optional, usually supervisors handle this)
gen_server:stop(my_counter),
io:format("Counter stopped.~n").When to Use Custom Behaviors
Custom OTP behaviors are powerful, but not every component needs one. Consider creating a custom behavior when:
- You find yourself writing similar
gen_serverorgen_statemboilerplate repeatedly. - You want to enforce a specific pattern or interface across multiple components.
- You need to provide a simpler, higher-level API for a complex underlying process.
- You are building a reusable library or framework component.
Quick Check
You've learned about custom OTP behaviors. Let's test your understanding.
Recap & Next Steps
You've explored the world of custom OTP behaviors!
- We saw that custom behaviors allow you to encapsulate common patterns.
- They typically consist of a **behavior module** (public API) and a **callback module** (logic).
- By wrapping existing behaviors like
gen_server, you can create powerful, reusable components.
Mastering custom behaviors empowers you to build highly modular and consistent Erlang applications.
자주 묻는 질문
“사용자 지정 OTP 동작” 강의는 무료인가요?
네 — “사용자 지정 OTP 동작” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 지정 OTP 동작”에서 뭘 배우나요?
OTP 동작의 구조와 공통 패턴을 캡슐화하는 사용자 지정 일반 동작을 만드는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Erlang OTP: Distributed & Fault-Tolerant Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“사용자 지정 OTP 동작” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.