Паттерны проектирования — это типовые решения распространённых проблем в разработке программного обеспечения. Это не готовый код, а концепция, которую можно адаптировать под конкретные нужды.
Основные характеристики:
Решают проблемы создания объектов:
Singleton (Одиночка)
AppCompatActivity
, Application
классobject DatabaseHelper {
fun queryData() { ... }
}
Factory (Фабрика)
interface View {
fun draw()
}
class ViewFactory {
fun createView(type: String): View {
return when(type) {
"button" -> ButtonView()
else -> TextView()
}
}
}
Builder (Строитель)
AlertDialog.Builder
в Androidval dialog = AlertDialog.Builder(context)
.setTitle("Title")
.setMessage("Message")
.create()
Организация классов и объектов:
Adapter (Адаптер)
RecyclerView.Adapter
в Androidclass UserAdapter(private val users: List<User>) :
RecyclerView.Adapter<UserAdapter.ViewHolder>() {
// Реализация адаптера
}
Decorator (Декоратор)
ContextWrapper
в Androidval decoratedContext = ContextThemeWrapper(baseContext, R.style.AppTheme)
Facade (Фасад)
Retrofit
библиотекаinterface ApiService {
@GET("users")
fun getUsers(): Call<List<User>>
}
Решают задачи эффективного взаимодействия объектов:
Observer (Наблюдатель)
LiveData
в AndroidliveData.observe(this) { data ->
// Обновление UI
}
Strategy (Стратегия)
interface SortStrategy {
fun sort(items: List<Int>): List<Int>
}
class BubbleSort : SortStrategy { ... }
class QuickSort : SortStrategy { ... }
Command (Команда)
Runnable
в Androidval command = Runnable {
// Выполнение действия
}
handler.post(command)
MVVM (Model-View-ViewModel)
// ViewModel
class UserViewModel : ViewModel() {
val users: LiveData<List<User>> = repository.getUsers()
}
// Activity/Fragment (View)
viewModel.users.observe(viewLifecycleOwner) { users ->
adapter.submitList(users)
}
Repository
class UserRepository(
private val localDataSource: UserLocalDataSource,
private val remoteDataSource: UserRemoteDataSource
) {
fun getUsers(): LiveData<List<User>> {
// Логика получения данных
}
}
Dependency Injection (Внедрение зависимостей)
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideRepository(): UserRepository {
return UserRepositoryImpl()
}
}
Совет: На собеседовании лучше подробно рассказать о 2-3 паттернах, которые вы реально применяли в проектах, с конкретными примерами.