Clean Architecture
در فرانتاند، ما داریم با:
- UI Components
- State Management
- Business Logic
- Data Access (APIs)
- Utilities
سر و کله میزنیم.
حالا Clean Architecture میگه:
یعنی UI نباید مستقیم به API وابسته باشه، بلکه باید به Abstractions وابسته باشه.
یه ساختار سادهش به این شکله:
src/
├─ domain/ ← business logic (entities, use-cases)
├─ application/ ← orchestrators, services, interfaces
├─ infrastructure/← API, DB, external libs implementations
├─ presentation/ ← UI (React/Next components)
└─ shared/ ← utils, constants
مثال واقعی
فرض کنیم میخوای کاربر لاگین کنه.
- Domain Layer
// domain/use-cases/login.usecase.ts
export class LoginUseCase {
constructor(private authRepo: AuthRepository) {}
async execute(credentials) {
return this.authRepo.login(credentials);
}
}
- Application Layer
// application/services/auth.service.ts
export const authService = (useCase: LoginUseCase) => ({
login: data => useCase.execute(data),
});
- Infrastructure (API)
// infrastructure/implementations/auth.api.ts
export class AuthApiRepository {
async login(credentials) {
const res = await fetch("/api/login", {
method: "POST",
body: JSON.stringify(credentials),
});
return res.json();
}
}
- Presentation (React Component)
const LoginForm = ({ authService }) => {
const handleSubmit = async () => {
const user = await authService.login({ email, password });
console.log("Logged In", user);
};
return <button onClick={handleSubmit}>Login</button>;
};
نتیجه نهایی :
- تستپذیری بالا
- حجم باگ کمتر
- قابلیت جایگزینی تکنولوژی (fetch → axios) بدون تغییر UI
- کد تمیز و قابل نگهداری
- توسعه سریعتر در تیمهای بزرگ
جمع بندی
الگوهای طراحی در فرانتاند تنها مجموعهای از بهترینها نیستند، بلکه روشی سیستماتیک برای حل مسائل معمول هستند. انتخاب الگوی مناسب به اندازه پروژه، تیم و نیازهای کسبوکار بستگی دارد. مهمترین نکته حفظ ثبات در پروژه و تطبیق الگوها با شرایط خاص هر پروژه است.
نکته طلایی: بهترین الگو، الگویی است که تیم شما آن را درک کند، نگهداری آن آسان باشد و نیازهای پروژه شما را برآورده سازد