Knowledge / Computer Science and Engineering / Design patterns

Design patterns

Computer Science and Engineering (B.E./B.Tech) · Software engineering · free study notes for exams, placements and interviews

In short

A design pattern is a named, reusable solution to a problem that recurs in object-oriented design - not code to copy, but a structure of classes and objects plus the trade-offs it brings. The standard catalogue is the 23 "Gang of Four" (GoF) patterns of Gamma, Helm, Johnson and Vlissides (1994), grouped as creational, structural and behavioural. Patterns are examined in university Software Engineering and Object-Oriented Analysis and Design papers (AICTE model curriculum / CBCS), in UGC-NET Computer Science, ISRO and NIELIT papers; current GATE CSE syllabus does not carry software engineering, so treat it as a placement and university topic. In interviews they are near-certain: Indian service companies (TCS, Infosys, Wipro, Cognizant, Accenture, Capgemini) ask them around Java/Spring, and product companies (Flipkart, Zomato, Swiggy, Razorpay, PhonePe, Zoho, Freshworks) ask you to name and apply them in a design round.

Explained

What a pattern is, and the vocabulary

Principles that generate the patterns

Creational patterns (5)

Structural patterns (7)

Behavioural patterns (11)

Patterns in frameworks, and compound patterns

Key points

Examples

1. Thread-safe Singleton - three correct forms, one wrong one

// (a) WRONG under concurrency: two threads can both see instance == null
static Logger get(){ if (inst == null) inst = new Logger(); return inst; }

// (b) Double-checked locking - volatile is mandatory
class Logger {
  private static volatile Logger inst;
  private Logger(){}
  static Logger get(){
    if (inst == null) {                       // 1st check, no lock
      synchronized (Logger.class) {
        if (inst == null) inst = new Logger();// 2nd check, under lock
      }
    } return inst;
  }
}
// (c) Bill Pugh holder - lazy, no locking
class Cfg { private Cfg(){} 
  private static class H { static final Cfg I = new Cfg(); }
  static Cfg get(){ return H.I; } }
// (d) enum singleton - serialization- and reflection-safe
enum Registry { INSTANCE; private final Map<String,String> m = new HashMap<>(); }

Note: Spring's default singleton bean scope means one instance per application context, not one per JVM - a standard interview trap.

2. Strategy removes a conditional - count the change A payment service supports UPI, card, net-banking and wallet, each with 3 variants: an if-else on 4 × 3 = 12 combinations sits in one method that must be edited for every new mode. With Strategy you add 1 class per mode and the service never changes.

interface Payment { long charge(long paise); }                 // amounts in paise
class Upi implements Payment { public long charge(long p){ return p; } }        // 0% MDR
class Card implements Payment { public long charge(long p){ return p + p*2/100; } } // 2%
class Checkout { private final Payment p; Checkout(Payment p){ this.p = p; }
  long pay(long amt){ return p.charge(amt); } }

For ₹2,000 (200000 paise): UPI → ₹2,000.00; Card → 200000 + 4000 = 204000 paise = ₹2,040.00.

3. Decorator - priced add-ons on a base product Base Masala Chai ₹25; decorators: extra milk ₹10, ginger ₹5, large ₹15. new Large(new Ginger(new ExtraMilk(new MasalaChai()))) → cost = 25 + 10 + 5 + 15 = ₹55. With subclassing you would need one class per combination: 3 independent add-ons → 2³ = 8 subclasses; with Decorator, 1 base + 3 decorators = 4 classes, and any of the 8 combinations is built at run time.

4. Bridge - avoiding the class explosion Shapes {Circle, Square, Triangle} to be drawn by renderers {SVG, Canvas, PDF, Printer}.

Classes neededInheritance (m × n)Bridge (m + n)
3 shapes × 4 renderers127
5 shapes × 6 renderers3011

5. Flyweight - memory saved on a map view A metro-map screen shows 2,00,000 station/stop markers. Each marker object = 64 bytes of intrinsic state (icon reference, colour, label style) + 16 bytes of extrinsic state (x, y).

6. "Name the pattern" - the classic exam question

ScenarioPattern
Hibernate returns a stub object and hits the DB only when a getter is calledProxy (virtual)
BufferedInputStream wraps a FileInputStreamDecorator
One ReportService method fixes the steps; subclasses override fetchData()Template Method
A leave request escalates manager → HR → director until approvedChain of Responsibility
An order object behaves differently as Placed / Shipped / CancelledState
Legacy SOAP gateway used through your new PaymentGateway interfaceAdapter
Dashboard widgets refresh when the data model updatesObserver
Pizza.Builder().thinCrust().extraCheese().build()Builder
One TravelFacade.book() hides flight, hotel, payment and SMS subsystemsFacade
Folder containing files and sub-folders, both with getSize()Composite

Comparison table - the four confusable pairs

PairSame structure?Difference in intent
Strategy vs StateYesClient picks the algorithm vs object changes its own state and transitions
Adapter vs FacadeNoConvert one interface vs simplify many
Decorator vs ProxyYesAdd responsibilities vs control/defer access
Factory Method vs Abstract FactoryNoSubclass hook for one product vs object creating a product family

Where it is used

Interview questions

Common mistakes

Related topics

Low-level design (object-oriented design) interviews · Requirements engineering and UML · Software architecture: monoliths and microservices · Clean code and code reviews · Object-oriented programming concepts in Java · Test automation and TDD

Open in the Knowledge reader →Find jobs →