惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Palo Alto Networks Blog
Martin Fowler
Martin Fowler
T
Threatpost
D
Docker
S
Schneier on Security
M
MIT News - Artificial intelligence
G
Google Developers Blog
L
LINUX DO - 热门话题
J
Java Code Geeks
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
人人都是产品经理
人人都是产品经理
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
U
Unit 42
C
CERT Recently Published Vulnerability Notes
The GitHub Blog
The GitHub Blog
Simon Willison's Weblog
Simon Willison's Weblog
NISL@THU
NISL@THU
MongoDB | Blog
MongoDB | Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Heimdal Security Blog
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
P
Privacy International News Feed
P
Proofpoint News Feed
O
OpenAI News
B
Blog
腾讯CDC
F
Full Disclosure
Apple Machine Learning Research
Apple Machine Learning Research
T
Tor Project blog
H
Hacker News: Front Page
Project Zero
Project Zero
Hugging Face - Blog
Hugging Face - Blog
C
Cisco Blogs
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Software Design Patterns
Kashaf Abdul · 2026-05-11 · via DEV Community

Introduction

Design patterns are proven solutions to common software design problems. They represent best practices evolved over time by experienced developers. Think of them as blueprints you can customize to solve recurring design problems in your code.

Part 1: CREATIONAL PATTERNS

Focus: Object creation mechanisms


1. Factory Method

Problem: Create objects without specifying exact class

Use when: Object type decided at runtime

// Product classes
class Car {
  drive() { console.log("Driving car"); }
}

class Bike {
  ride() { console.log("Riding bike"); }
}

// Factory
class VehicleFactory {
  static create(type) {
    if (type === "car") return new Car();
    if (type === "bike") return new Bike();
  }
}

// Usage
const myCar = VehicleFactory.create("car");
myCar.drive(); // Driving car

Enter fullscreen mode Exit fullscreen mode


2. Abstract Factory

Problem: Create families of related objects

Use when: System needs to be independent of how products are created

// Abstract products
class WinButton { render() { return "Windows Button"; } }
class MacButton { render() { return "Mac Button"; } }

// Abstract factory
class UIFactory {
  static getFactory(os) {
    if (os === "win") return new WinFactory();
    return new MacFactory();
  }
}

class WinFactory {
  createButton() { return new WinButton(); }
}

// Usage
const factory = UIFactory.getFactory("win");
const button = factory.createButton();
console.log(button.render()); // Windows Button

Enter fullscreen mode Exit fullscreen mode


3. Singleton

Problem: Ensure only one instance exists

Use when: Need single point of control (database connection, config)

class Database {
  constructor() {
    if (Database.instance) return Database.instance;
    this.connection = "Connected to DB";
    Database.instance = this;
  }

  query(sql) { console.log(`Executing: ${sql}`); }
}

// Usage
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true

Enter fullscreen mode Exit fullscreen mode


4. Prototype

Problem: Create objects by cloning existing ones

Use when: Object creation is expensive

const carPrototype = {
  wheels: 4,
  start() { console.log("Engine started"); },
  clone() { return Object.create(this); }
};

// Usage
const sportsCar = carPrototype.clone();
sportsCar.color = "red";
sportsCar.start(); // Engine started

Enter fullscreen mode Exit fullscreen mode


5. Builder

Problem: Construct complex objects step by step

Use when: Object has many optional parts

class Computer {
  constructor() {
    this.parts = [];
  }
}

class ComputerBuilder {
  constructor() {
    this.parts = [];
  }

  addCPU() { this.parts.push("Intel i7"); return this; }
  addRAM() { this.parts.push("16GB DDR4"); return this; }
  addSSD() { this.parts.push("512GB NVMe"); return this; }
  build() { return this.parts; }
}

// Usage
const gamingPC = new ComputerBuilder()
  .addCPU()
  .addRAM()
  .addSSD()
  .build();

console.log(gamingPC); // ["Intel i7", "16GB DDR4", "512GB NVMe"]

Enter fullscreen mode Exit fullscreen mode


Part 2: STRUCTURAL PATTERNS

Focus: Class and object composition


6. Adapter

Problem: Make incompatible interfaces work together

Use when: Need to integrate old code with new system

// Old system
class OldAPI {
  getUserData() { return { name: "John", age: 30 }; }
}

// New expected format
class UserAdapter {
  constructor(oldAPI) { 
    this.oldAPI = oldAPI; 
  }

  getUser() {
    const data = this.oldAPI.getUserData();
    return `${data.name} is ${data.age} years old`;
  }
}

// Usage
const oldAPI = new OldAPI();
const adapter = new UserAdapter(oldAPI);
console.log(adapter.getUser()); // John is 30 years old

Enter fullscreen mode Exit fullscreen mode


7. Bridge

Problem: Separate abstraction from implementation

Use when: Want to avoid permanent binding between abstraction and implementation

// Implementation
class LEDTV { on() { console.log("LED TV ON"); } }
class OLEDTV { on() { console.log("OLED TV ON"); } }

// Abstraction
class Remote {
  constructor(tv) { this.tv = tv; }
  powerOn() { this.tv.on(); }
}

// Usage
const ledTV = new LEDTV();
const remote = new Remote(ledTV);
remote.powerOn(); // LED TV ON

Enter fullscreen mode Exit fullscreen mode


8. Composite

Problem: Treat individual and group objects uniformly

Use when: Need tree structure of objects

class File {
  constructor(name) { this.name = name; }
  display() { console.log(`File: ${this.name}`); }
}

class Folder {
  constructor(name) {
    this.name = name;
    this.children = [];
  }

  add(item) { this.children.push(item); }

  display() {
    console.log(`Folder: ${this.name}`);
    this.children.forEach(child => child.display());
  }
}

// Usage
const file1 = new File("doc.txt");
const file2 = new File("image.jpg");
const folder = new Folder("Documents");

folder.add(file1);
folder.add(file2);
folder.display();

Enter fullscreen mode Exit fullscreen mode


9. Decorator

Problem: Add behavior dynamically without modifying class

Use when: Need to extend functionality at runtime

class Coffee {
  cost() { return 5; }
  description() { return "Coffee"; }
}

class MilkDecorator {
  constructor(coffee) { this.coffee = coffee; }
  cost() { return this.coffee.cost() + 2; }
  description() { return this.coffee.description() + ", Milk"; }
}

// Usage
let myCoffee = new Coffee();
myCoffee = new MilkDecorator(myCoffee);
console.log(myCoffee.description()); // Coffee, Milk
console.log(myCoffee.cost()); // 7

Enter fullscreen mode Exit fullscreen mode


10. Facade

Problem: Provide simple interface to complex subsystem

Use when: Want to hide system complexity

// Complex subsystems
class CPU { freeze() { console.log("CPU frozen"); } }
class Memory { load() { console.log("Memory loaded"); } }
class HardDrive { read() { console.log("Hard drive reading"); } }

// Facade
class Computer {
  constructor() {
    this.cpu = new CPU();
    this.memory = new Memory();
    this.hdd = new HardDrive();
  }

  start() {
    this.cpu.freeze();
    this.memory.load();
    this.hdd.read();
    console.log("Computer started!");
  }
}

// Usage
const pc = new Computer();
pc.start(); // Clean, simple interface

Enter fullscreen mode Exit fullscreen mode


11. Flyweight

Problem: Share objects to support large numbers efficiently

Use when: Many similar objects, memory is concern

// Shared object
class Character {
  constructor(char) { this.char = char; }
  display(x, y) { console.log(`'${this.char}' at (${x},${y})`); }
}

// Factory
class CharacterFactory {
  constructor() { this.chars = {}; }

  get(char) {
    if (!this.chars[char]) {
      this.chars[char] = new Character(char);
    }
    return this.chars[char];
  }
}

// Usage
const factory = new CharacterFactory();
const a1 = factory.get('A');
const a2 = factory.get('A');
console.log(a1 === a2); // true (same object)

Enter fullscreen mode Exit fullscreen mode


12. Proxy

Problem: Control access to object

Use when: Need lazy loading, access control, logging

class RealImage {
  constructor(filename) {
    this.filename = filename;
    this.loadFromDisk();
  }

  loadFromDisk() { console.log(`Loading ${this.filename}`); }
  display() { console.log(`Displaying ${this.filename}`); }
}

class ProxyImage {
  constructor(filename) {
    this.filename = filename;
    this.realImage = null;
  }

  display() {
    if (!this.realImage) {
      this.realImage = new RealImage(this.filename);
    }
    this.realImage.display();
  }
}

// Usage
const image = new ProxyImage("photo.jpg");
image.display(); // Loads and displays
image.display(); // Only displays (already loaded)

Enter fullscreen mode Exit fullscreen mode


Part 3: BEHAVIORAL PATTERNS

Focus: Object communication and responsibility


13. Command

Problem: Encapsulate request as object

Use when: Need to parameterize, queue, or log requests

class Light {
  on() { console.log("Light ON"); }
  off() { console.log("Light OFF"); }
}

class Command {
  constructor(receiver) { this.receiver = receiver; }
  execute() {}
}

class LightOnCommand extends Command {
  execute() { this.receiver.on(); }
}

class Remote {
  setCommand(cmd) { this.command = cmd; }
  press() { this.command.execute(); }
}

// Usage
const light = new Light();
const onCommand = new LightOnCommand(light);
const remote = new Remote();

remote.setCommand(onCommand);
remote.press(); // Light ON

Enter fullscreen mode Exit fullscreen mode


14. Iterator

Problem: Access elements sequentially without exposing structure

Use when: Need to traverse collection

class Playlist {
  constructor() { this.songs = []; }

  add(song) { this.songs.push(song); }

  [Symbol.iterator]() {
    let index = 0;
    let songs = this.songs;

    return {
      next() {
        if (index < songs.length) {
          return { value: songs[index++], done: false };
        }
        return { done: true };
      }
    };
  }
}

// Usage
const playlist = new Playlist();
playlist.add("Song 1");
playlist.add("Song 2");

for (let song of playlist) {
  console.log(song); // Song 1, Song 2
}

Enter fullscreen mode Exit fullscreen mode


15. Mediator

Problem: Reduce direct communication between objects

Use when: Many-to-many communication needed

class ChatRoom {
  constructor() { this.users = []; }

  add(user) {
    this.users.push(user);
    user.room = this;
  }

  send(message, from) {
    this.users.forEach(user => {
      if (user !== from) {
        user.receive(message, from.name);
      }
    });
  }
}

class User {
  constructor(name) { this.name = name; }

  send(message) { this.room.send(message, this); }

  receive(message, from) {
    console.log(`${this.name} got: "${message}" from ${from}`);
  }
}

// Usage
const room = new ChatRoom();
const ali = new User("Ali");
const ahmed = new User("Ahmed");

room.add(ali);
room.add(ahmed);
ali.send("Hello!"); // Ahmed got: "Hello!" from Ali

Enter fullscreen mode Exit fullscreen mode


16. Memento

Problem: Save and restore object state

Use when: Need undo/redo functionality

class Editor {
  constructor() { this.content = ""; }

  write(text) { this.content += text; }
  save() { return new Memento(this.content); }
  restore(m) { this.content = m.content; }
}

class Memento {
  constructor(content) { this.content = content; }
}

// Usage
const editor = new Editor();
editor.write("Hello ");
const saved = editor.save();
editor.write("World");

console.log(editor.content); // Hello World

editor.restore(saved);
console.log(editor.content); // Hello

Enter fullscreen mode Exit fullscreen mode


17. Observer

Problem: Notify multiple objects about state changes

Use when: One-to-many dependency needed

class NewsChannel {
  constructor() {
    this.subscribers = [];
    this.news = "";
  }

  subscribe(sub) { this.subscribers.push(sub); }

  setNews(news) {
    this.news = news;
    this.notify();
  }

  notify() {
    this.subscribers.forEach(sub => sub.update(this.news));
  }
}

class Subscriber {
  constructor(name) { this.name = name; }
  update(news) { console.log(`${this.name} got news: ${news}`); }
}

// Usage
const channel = new NewsChannel();
const ali = new Subscriber("Ali");

channel.subscribe(ali);
channel.setNews("Breaking: Design Patterns!");
// Ali got news: Breaking: Design Patterns!

Enter fullscreen mode Exit fullscreen mode


18. State

Problem: Change behavior based on internal state

Use when: Object has many states with different behaviors

class TrafficLight {
  constructor() { this.state = new RedState(); }

  change() {
    this.state.handle();
    this.state = this.state.next();
  }
}

class RedState {
  handle() { console.log("RED: Stop"); }
  next() { return new GreenState(); }
}

class GreenState {
  handle() { console.log("GREEN: Go"); }
  next() { return new YellowState(); }
}

class YellowState {
  handle() { console.log("YELLOW: Wait"); }
  next() { return new RedState(); }
}

// Usage
const light = new TrafficLight();
light.change(); // RED: Stop
light.change(); // GREEN: Go
light.change(); // YELLOW: Wait

Enter fullscreen mode Exit fullscreen mode


19. Strategy

Problem: Select algorithm at runtime

Use when: Multiple algorithms for same task

class Payment {
  constructor(strategy) { this.strategy = strategy; }
  pay(amount) { this.strategy.pay(amount); }
}

class CreditCard {
  pay(amount) { console.log(`Paid $${amount} with Credit Card`); }
}

class PayPal {
  pay(amount) { console.log(`Paid $${amount} with PayPal`); }
}

class Crypto {
  pay(amount) { console.log(`Paid $${amount} with Bitcoin`); }
}

// Usage
const payment = new Payment(new CreditCard());
payment.pay(100); // Paid $100 with Credit Card

payment.strategy = new PayPal();
payment.pay(50); // Paid $50 with PayPal

Enter fullscreen mode Exit fullscreen mode


20. Template Method

Problem: Define skeleton with customizable steps

Use when: Steps are same but implementations differ

class DataProcessor {
  process() {
    this.loadData();
    this.processData();
    this.saveData();
  }

  loadData() { console.log("Loading data..."); }
  saveData() { console.log("Saving data..."); }
}

class CSVProcessor extends DataProcessor {
  processData() { console.log("Processing CSV data"); }
}

class JSONProcessor extends DataProcessor {
  processData() { console.log("Processing JSON data"); }
}

// Usage
const csv = new CSVProcessor();
csv.process(); // Loading > Processing CSV > Saving

Enter fullscreen mode Exit fullscreen mode


21. Visitor

Problem: Add operations to objects without modifying them

Use when: Many unrelated operations on same objects

class Car {
  accept(visitor) { visitor.visitCar(this); }
}

class Bike {
  accept(visitor) { visitor.visitBike(this); }
}

class TaxCalculator {
  visitCar(car) { console.log("Car tax: $200"); }
  visitBike(bike) { console.log("Bike tax: $50"); }
}

class InsuranceCalculator {
  visitCar(car) { console.log("Car insurance: $500"); }
  visitBike(bike) { console.log("Bike insurance: $100"); }
}

// Usage
const car = new Car();
const tax = new TaxCalculator();
car.accept(tax); // Car tax: $200

Enter fullscreen mode Exit fullscreen mode


Quick Reference Table

Need Pattern
Need one instance only Singleton
Need to create objects Factory / Abstract Factory
Need to add features dynamically Decorator
Need to notify others of changes Observer
Need to choose algorithm at runtime Strategy
Need to undo/redo actions Command / Memento
Need to traverse a collection Iterator
Need to simplify complex subsystem Facade
Need to handle many similar objects Flyweight
Need to control access to object Proxy

When to Use What?

  • Need one instance only? → Singleton
  • Need to create objects? → Factory / Abstract Factory
  • Need to add features? → Decorator
  • Need to notify others? → Observer
  • Need to choose algorithm? → Strategy
  • Need to undo actions? → Command / Memento
  • Need to traverse collection? → Iterator
  • Need to simplify complex system? → Facade

Conclusion

Design patterns are not templates to copy-paste, but guidelines to solve common problems. Master these 23 patterns, and you'll:

  • Write more maintainable code
  • Communicate better with other developers
  • Solve design problems faster
  • Build more flexible systems

Remember: Don't force patterns where they're not needed. Use them when they genuinely solve a problem! 🎯


Resources


Written by Kashaf Abdullah

Software Engineer | MERN Stack | Web Development