🚀 Mastering Creational Design Patterns in Software Development
Design Patterns is a best practice. It provide solutions to common coding problems, making applications more maintainable, scalable, and reusable.
Types of Design Patterns:
🛠️ Creational Design Patterns
These patterns focus on object creation while maintaining flexibility and efficiency.
1️⃣ Singleton Pattern 🏆 (Ensure creating a single instance of a class)
✔️ Useful for database connections, logging, and managing app state.
class SingletonClass {
static SingletonClass? _instance;
SingletonClass._();
static getInstance() {
return _instance ??= SingletonClass._();
}
}
void main() {
var obj1 = SingletonClass.getInstance();
var obj2 = SingletonClass.getInstance();
print(obj1 == obj2); // ✅ True, same instance
}
Recommended by LinkedIn
2️⃣ Prototype Pattern 🎭 (Create object copies efficiently)
✔️ Helps create clones of objects without modifying the original instance.
import 'package:flutter/material.dart';
@immutable
class Person {
final String name;
final String lastname;
final int age;
final String nation;
const Person(
{required this.name,
required this.lastname,
required this.age,
required this.nation});
Person clone() {
return Person(name: name, lastname: lastname, age: age, nation: nation);
}
Person copyWith({
String? name,
String? lastname,
int? age,
String? nation,
}) {
return Person(
name: name ?? this.name, // ✅ If name is not provided, keep the original
lastname: lastname ?? this.lastname,
age: age ?? this.age,
nation: nation ?? this.nation,
);
}
}
void main() {
Person person =
Person(name: 'raju', lastname: 'guru', age: 34, nation: 'india');
Person person1 = person.clone();
// person1.name='ramu';// can not edit name.
print(person1.name);
Person person2 = person.copyWith(name: 'ramu');//can edit name
print(person2.name);
}
3️⃣ Factory Pattern 🏭 (Create objects dynamically based on conditions)
✔️ The Factory Pattern process by providing a centralized method(class) to create objects, promoting flexibility and scalability.
abstract class Employee {
void work();
}
class Programmer extends Employee {
@override
void work() {
print('coding an app');
}
}
class HRManager extends Employee {
@override
void work() {
print('recruiting people');
}
}
class Boss extends Employee {
@override
void work() {
print('leading the people');
}
}
enum EmployeeType { hr, boss, programmer }
class FactoryMethodPattern {
static getEmployee(EmployeeType type) {
switch (type) {
case EmployeeType.programmer:
return Programmer();
case EmployeeType.hr:
return HRManager();
case EmployeeType.boss:
return Boss();
default:
return Programmer();
}
}
}
void main() {
Employee getEmployee = FactoryMethodPattern.getEmployee(EmployeeType.hr);
getEmployee.work();
}
✨ Which pattern do you use most in your projects? Comment below! 👇 #Flutter #Dart #DesignPatterns #SoftwareEngineering #Coding #Dart #Flutter