Factory Pattern in Java: Creating Objects the Smart Way Let’s be honest. new is one of the most overused keywords in Java. Every time you create an object directly, you tie your code to a specific implementation. The Factory Pattern fixes that. It lets you delegate object creation so your code stays flexible and clean. The idea: Instead of calling constructors everywhere, you ask a “factory” to give you the right object based on your need. Example: interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } } class ShapeFactory { public Shape getShape(String type) { if (type.equalsIgnoreCase("CIRCLE")) return new Circle(); if (type.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); return null; } } How you use it: ShapeFactory factory = new ShapeFactory(); Shape shape = factory.getShape("CIRCLE"); shape.draw(); Why it matters You separate creation from logic. Your code becomes easy to maintain and extend. Adding a new shape? Just create a new class — no need to touch existing logic. Where you’ll see it Spring Beans (IoC container acts like a factory) Database connections Notification or message services The Factory Pattern is your first step toward writing loosely coupled, testable code. It’s simple but forms the foundation of scalable systems. Which factory-like pattern have you seen most in production — Factory, Abstract Factory, or Builder? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
Umar Ashraf Lone’s Post
More Relevant Posts
-
Factory Pattern in Java: Creating Objects the Smart Way Let’s be honest. new is one of the most overused keywords in Java. Every time you create an object directly, you tie your code to a specific implementation. The Factory Pattern fixes that. It lets you delegate object creation so your code stays flexible and clean. The idea: Instead of calling constructors everywhere, you ask a “factory” to give you the right object based on your need. Example: interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } } class ShapeFactory { public Shape getShape(String type) { if (type.equalsIgnoreCase("CIRCLE")) return new Circle(); if (type.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); return null; } } How you use it: ShapeFactory factory = new ShapeFactory(); Shape shape = factory.getShape("CIRCLE"); shape.draw(); Why it matters You separate creation from logic. Your code becomes easy to maintain and extend. Adding a new shape? Just create a new class — no need to touch existing logic. Where you’ll see it Spring Beans (IoC container acts like a factory) Database connections Notification or message services The Factory Pattern is your first step toward writing loosely coupled, testable code. It’s simple but forms the foundation of scalable systems. Which factory-like pattern have you seen most in production — Factory, Abstract Factory, or Builder? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
Decorator Pattern in Java Sometimes you want to add features to an object. You do not want to modify the original class. You do not want to create many subclasses. The Decorator Pattern solves this. Use it when you want to extend behavior at runtime. Example interface Notifier { void send(String message); } class BasicNotifier implements Notifier { public void send(String message) { System.out.println("Sending notification: " + message); } } class EmailDecorator implements Notifier { private Notifier notifier; public EmailDecorator(Notifier notifier) { this.notifier = notifier; } public void send(String message) { notifier.send(message); System.out.println("Email sent"); } } class SmsDecorator implements Notifier { private Notifier notifier; public SmsDecorator(Notifier notifier) { this.notifier = notifier; } public void send(String message) { notifier.send(message); System.out.println("SMS sent"); } } Use it like this Notifier notifier = new SmsDecorator(new EmailDecorator(new BasicNotifier())); notifier.send("User registered"); Result • Sends base notification • Sends email • Sends SMS Clear benefits • Add features without touching the original class • No subclass explosion • Flexible and simple When to use • When you need optional features • When you want to avoid large inheritance hierarchies Takeaway The Decorator Pattern gives you flexibility. You attach new behavior without breaking existing code. #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
Primitives vs Wrappers in Java: A Practical Balance for Performance and API Design 💡 In Java, choosing between primitive types (int, boolean, long) and their wrapper counterparts (Integer, Boolean, Long) isn’t just a speed race—it shapes how you model nullability, API contracts, and data flows. 🚀 Primitives win on performance and memory: fewer objects, no nulls, and straightforward arithmetic. They’re the default for local variables and tight loops. 🧭 Wrappers unlock object‑oriented conveniences: nullability, easy use in generics, and compatibility with reflection or frameworks. But boxing/unboxing and higher memory usage can sneak into hot paths. Key takeaways: - Use primitives in performance‑sensitive code and internal math. - Use wrappers in DTOs, API surfaces, or data stores where nulls or optional values matter. - Prefer primitive streams (IntStream, LongStream) to avoid boxing in data pipelines. - If you need to express absence with primitives, consider OptionalInt/OptionalLong rather than nulls. - When working with large, memory‑sensitive collections, consider primitive‑specific collections from third‑party libraries. - Be mindful of NPEs when a wrapper value is null. Bottom line: balance is design‑driven, not dogmatic. Align your choice with API guarantees and performance budgets. What’s your take? Have you faced a scenario where the primitive vs wrapper choice changed performance or design outcomes? What specific suggestions would you add to improve this post (e.g., with a short code snippet)? #Java #JavaPerformance #PrimitivesVsWrappers #SoftwareEngineering #Programming
To view or add a comment, sign in
-
💭 Ever wondered why your Java string operations feel slow sometimes? String vs StringBuilder vs StringBuffer — same syntax, different game. 1️⃣ STRING – Immutable & Simple Once created → it can’t be changed. Every modification creates a new object. Example: String s = "Java"; s = s + " Rocks!"; 👉 Two objects created — one discarded. ✅ Best for fixed text (like constants, messages, config values) ⚠️ Avoid in loops or repeated concatenations — it’s memory heavy 🔍 Why immutable? Thread-safe Used in String Pool for performance Prevents accidental modification 2️⃣ STRINGBUILDER – Mutable & Fast Edits the same object instead of creating new ones. Perfect for building large strings efficiently. Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); ✅ Fast & memory-efficient ✅ Ideal for loops and dynamic string operations ⚠️ Not thread-safe — avoid in multi-threaded code 3️⃣ STRINGBUFFER – Mutable & Thread-Safe Same as StringBuilder but synchronized. That means only one thread can modify it at a time. Example: StringBuffer sb = new StringBuffer("Sync"); sb.append(" Safe"); ✅ Safe for multi-threaded applications ⚠️ Slower than StringBuilder due to synchronization
To view or add a comment, sign in
-
💭 Heap vs Stack Memory in Java — The Real Difference (Explained Simply) 🧠 You’ve probably heard these terms a hundred times: > “Object is stored in the heap.” “Local variable goes on the stack.” But what does that really mean? 🤔 Let’s break it down 👇 --- 🔹 1️⃣ Stack — The Short-Term Memory The stack stores: Method calls 🧩 Local variables References to objects in the heap It’s fast, organized in LIFO (Last-In, First-Out) order, and automatically cleared when a method ends. Once a method returns, all its stack frames vanish — poof 💨 Example 👇 void test() { int x = 10; // stored in stack String s = "Java"; // reference in stack, object in heap } --- 🔹 2️⃣ Heap — The Long-Term Memory The heap is where all objects live 🏠 It’s shared across threads and managed by the Garbage Collector. It’s slower than the stack — but it’s what makes Java flexible and object-oriented. When you do: Person p = new Person("Tushar"); → p (the reference) lives on the stack, → the actual Person object lives in the heap. --- ⚡ Pro Tip Memory leaks usually happen in the heap, while StackOverflowError (yes, the real one 😅) comes from — you guessed it — an overfilled stack due to deep recursion or infinite method calls. --- 💬 Your Turn Do you monitor heap and stack usage in your apps (via tools like VisualVM or JConsole)? 👇 Or do you just “trust the JVM”? #Java #MemoryManagement #JVM #GarbageCollection #BackendDevelopment #CleanCode #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
Adapter Pattern in Java Problem You have code that works with one type of interface. You get a new class that does similar work but exposes a different method. Your existing code cannot use it directly. Adapter Pattern solves this. It lets you connect two incompatible classes without touching existing code. Example You already have this interface: interface PaymentProcessor { void pay(int amount); } A new payment service arrives but uses a different method: class NewPaymentService { void makePayment(int amount) { System.out.println("Payment processed"); } } Create an adapter that matches your existing interface: class PaymentAdapter implements PaymentProcessor { private NewPaymentService service; public PaymentAdapter(NewPaymentService service) { this.service = service; } public void pay(int amount) { service.makePayment(amount); } } Use it like this: PaymentProcessor processor = new PaymentAdapter(new NewPaymentService()); processor.pay(500); Key points • Adapter converts one interface into another. • It avoids modifying existing working code. • It helps integrate new systems smoothly. When to use • When a new class does not match existing method signatures. • When you integrate legacy code with new APIs. Takeaway The Adapter Pattern protects your codebase. You add new functionality without breaking anything. #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
How Java Manages Memory (And Why You Should Care) Good code isn’t just about logic. It’s about how efficiently your program uses memory. Java does a lot for you behind the scenes, but knowing how memory works helps you write faster, more stable applications. Java memory is divided into two main areas: 1. Stack Memory Stores method calls and local variables. Each thread has its own stack. Fast and automatically cleared when a method ends. Example: int a = 10; int b = 20; int sum = a + b; All of these live in the stack. 2. Heap Memory Stores objects and instance variables. Shared among all threads. Managed by the Garbage Collector (GC). Example: User user = new User("Umar"); user reference lives on the stack, but the User object lives on the heap. Garbage Collection (GC) Java automatically frees memory from unused objects. You don’t need to manually delete anything. But… you still need to write memory-friendly code. Pro tips for developers Avoid unnecessary object creation. Release large data structures when no longer needed. Use profiling tools like VisualVM or JConsole to monitor memory. Understanding memory helps you prevent leaks, optimize performance, and build scalable systems. How well do you understand what happens inside the JVM when your code runs? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
⚙️ What Really Happens When You Create an Object in Java (new Keyword Deep Dive) 🧠 We’ve all done this a thousand times 👇 User user = new User("Tushar", 27); …but have you ever wondered what really happens under the hood when you hit new? 🤔 Let’s peel it back step by step 👇 --- 🔹 1️⃣ Class Loading Before the JVM can create an object, it first checks if the class is loaded into memory. If not — the ClassLoader brings it in from disk, verifies it, and stores metadata in the method area. So User.class is now ready to roll 📦 --- 🔹 2️⃣ Memory Allocation The JVM allocates memory for that object inside the heap (not the stack!) 🏠 How much? Enough to hold all instance variables defined in the class. Each new call = new memory slot in the heap. --- 🔹 3️⃣ Default Initialization Before your constructor runs, default values (like 0, false, or null) are assigned to all instance variables. This ensures your object is in a safe, predictable state — no garbage data lying around. --- 🔹 4️⃣ Constructor Call Once memory is ready, the constructor executes. That’s where your custom logic runs — assigning parameters, initializing resources, etc. At this stage, your object is fully constructed 🧱 --- 🔹 5️⃣ Reference Assignment Finally, the variable (user in this case) on the stack gets a reference (pointer) to the object in the heap. That’s how the stack and heap work together 💡 --- ⚡ The Takeaway The new keyword isn’t just object creation — it’s class loading + memory allocation + initialization + reference linking all in one powerful step 🚀 So next time you type new, remember — you’re orchestrating one of the most elegant parts of the JVM’s design. --- 💬 Your turn: Did you know all these steps were happening behind that tiny new keyword? 👇 Or did this post make you see object creation differently? #Java #JVM #MemoryManagement #ObjectCreation #BackendDevelopment #SoftwareEngineering #CleanCode #JavaDeveloper
To view or add a comment, sign in
-
Observer Pattern in Java When one object changes and many other objects need to react, you should not call them one by one. You need a clean way to notify all listeners. The Observer Pattern solves this. One object is the source. Many observers subscribe to updates. Simple example interface Observer { void update(String message); } interface Subject { void registerObserver(Observer observer); void notifyObservers(String message); } class NotificationService implements Subject { private List<Observer> observers = new ArrayList<>(); public void registerObserver(Observer observer) { observers.add(observer); } public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } } class User implements Observer { private String name; public User(String name) { this.name = name; } public void update(String message) { System.out.println(name + " received: " + message); } } Usage NotificationService service = new NotificationService(); service.registerObserver(new User("Umar")); service.registerObserver(new User("Ali")); service.notifyObservers("New update available"); Key points • Subject sends updates • Observers react • Loose coupling • Easy to extend Where it is used • Event systems • Messaging • UI frameworks Takeaway Observer Pattern builds a clean broadcast system. No direct dependency between sender and receivers. #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment
To view or add a comment, sign in
-
You should use 𝚂𝚝𝚛𝚒𝚗𝚐 𝚊 = “𝙷𝚎𝚕𝚕𝚘”, and not 𝚂𝚝𝚛𝚒𝚗𝚐 𝚊 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”) in Java. Here’s why. 👇 If you write Java, you deal with String objects all day long. But do you know the hidden memory optimization that saves your application from running out of space? It's the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥. 𝐒𝐭𝐫𝐢𝐧𝐠 𝐩𝐨𝐨𝐥, 𝐨𝐫 𝐭𝐡𝐞 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥, is a special storage area in the Java 𝐇𝐞𝐚𝐩 𝐦𝐞𝐦𝐨𝐫𝐲 where string literals are stored. The core idea is to avoid creating multiple duplicate String objects in memory when they have the same content. The String Pool is the 𝐤𝐞𝐲 to efficient, scalable code and a crucial JVM feature. When you declare a String literal (𝐒𝐭𝐫𝐢𝐧𝐠 𝐚 = "𝐇𝐞𝐥𝐥𝐨"), the JVM first checks the Pool. If the string already exists, the new variable will simply point to that existing object in the pool, avoiding new memory allocation. This optimization only works because Java String objects are 𝐢𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞. 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟷 = “𝙷𝚎𝚕𝚕𝚘”; 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟸 = “𝙷𝚎𝚕𝚕𝚘”; Both strings point to the same object in memory. So if you do: 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟸); // 𝚝𝚛𝚞𝚎 𝐖𝐡𝐞𝐧 𝐲𝐨𝐮 𝐰𝐫𝐢𝐭𝐞: 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟹 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”); It always 𝐟𝐨𝐫𝐜𝐞𝐬 the creation of a new object in the main Heap, outside the String Pool. So if you do: 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟹); // 𝚏𝚊𝚕𝚜𝚎 If you absolutely must use the new operator you can call .𝚒𝚗𝚝𝚎𝚛𝚗() on your string to explicitly move or fetch its reference from the Pool, forcing the JVM to 𝐫𝐞𝐮𝐬𝐞 𝐨𝐛𝐣𝐞𝐜𝐭𝐬. 𝚂𝚝𝚛𝚒𝚗𝚐 𝚜𝟹 = 𝚗𝚎𝚠 𝚂𝚝𝚛𝚒𝚗𝚐(“𝙷𝚎𝚕𝚕𝚘”).𝚒𝚗𝚝𝚎𝚛𝚗(); 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗(𝚜𝟷 == 𝚜𝟹); // 𝚝𝚛𝚞𝚎 What’s your favorite JVM optimization trick? Share in the comments! 👇 #Java #JVM #SoftwareEngineering #TechCareer #ProgrammingTips #MemoryManagement #PerformanceTuning #Coding
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development