Design patterns with real time example

design-patterns

Solution

These classic design patterns every developer should understand, because it helps us to communicate with other developer abstract level, and it makes us better designer.

Note: Adding brief definition with real life and Java API examples.

Creational

Way of creating objects, while hiding the creation logic.

Prototype : A fully initialized instance to be copied or cloned Example : A bakery that uses a prototype cake to create new cakes.

- `java.lang.Object#clone()`

Builder - Separates the construction of a complex object from its representation so that the same construction process can create different representations. Example : A software development team that creates new software using a variety of libraries and frameworks.

- java.lang.StringBuilder

Singleton - A class of which only a single instance can exist Example : President of a country

- java.lang.Runtime#getRuntime()

Factory Method - Creates a family of object types. Example : In an organisation HR works as factory method. Here development team request type of resource need to HR. Based on request type, HR provide resource to Development team.

- java.util.Calendar#getInstance()

Abstract Factory - Creates an instance of several families of classes Example : HP, Samsung and Dell laptops are uses Intel and AMD processor.

- javax.xml.parsers.DocumentBuilderFactory#newInstance()

Factory Method vs Abstract Factory

Structural

Structural patterns help create a large object(i.e. infrastructure) from small objects.

Proxy - Introduces a proxy layer between clients and services to add functionalities like caching or security.

- java.rmi.*, the whole API actually.

Composite - Gives an unified interface to a leaf and composite. Compose objects into tree structures to represent part-whole hierarchies i.e. an object represt as part and also represent whole. Example : File System in Operating Systems, Directories are composite and files are leaves. System call `Open` is single interface for both composite and leaf.

Decorator - Decorator design pattern is used to add the functionality by wrapping another class around the core class without modifying the core class. Example : 1) Adding discounts on an order 2) gun is a deadly weapon on it's own. But you can apply certain "decorations" to make it more accurate, silent and devastating.

- All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type.

Facade - Provide a unified interface to a set of interfaces in a subsystem, making the subsystem easier to use. Example : Control Panel, Event Manager.

- javax.faces.context.ExternalContext, which internally uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, et

Adapter - Adapter pattern is used when two unrelated interfaces need to work together. Example : Power Adapters

- java.util.Arrays#asList()

Flyweight - A space optimization technique that lets us use less memory by sharing data. Example : A software development team that uses a pool of database connections to reduce the overhead of creating and closing new connections.

- java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short and Long)

Behavioral

Behavioral patterns specially concerned with communication between Objects which helps loose coupling.

Chain of Responsibility is used to pass a request along a chain of handlers. Example : Loan or Leave approval process, Exception handling in Java.

- javax.servlet.Filter#doFilter()

Iterator - Traverse/Sequentially access the elements of a collection Example : A for loop in a programming language

- All implementations of java.util.Iterator & java.util.Enumeration

State - Allow an object to alter its behavior when its internal state changes Example : A traffic light that cycles through the states of red, yellow, and green. A vending machine that transitions through the states of idle, accepting money, dispensing product, and out of stock. A video game character that can be in the states of standing, walking, running, and jumping.

Observer - A one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically Example : A social media platform

- Publish/Subscribe JMS API

Visitor - Visitor pattern is used to add methods to different types of classes without altering those classes. Example : A database that performs different operations on different types of data. A web browser that renders different types of HTML elements.

Template - Defines a skeleton of an algorithm in an operation, and defers some steps to subclasses. Example : A cooking recipe that provides a step-by-step template for preparing a dish. A software development lifecycle that provides a template for developing and delivering software.

- All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.

- All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.

- javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.

- JMSTemplate HibernateTemplate and JdbcTemplate in Spring

Command - Command pattern is used when request is wrapped and passed to invoker which then inturn invokes the encapsulated command. Example : A remote control

- All implementations of java.lang.Runnable

Memento - Memento pattern is used to restore state of an object to a previous state. Example : save the state in a game & Undo/Redo operation in Windows, A text editor that allows users to undo and redo their actions. A database that allows users to rollback transactions.

- All implementations of java.io.Serializable

Mediator - Mediator pattern is used to provide a centralized communication medium between different objects. Example : Air Traffic Controller(ATC), Stock Exhange

Strategy - Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime. Example : Modes of transportation

- java.util.Comparator#compare(), executed by among others Collections#sort().

- javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).

- javax.servlet.Filter#doFilter()

Java implemented Design Patterns Design Pattern with Simple examples Useful link https://gitorko.github.io/post/design-patterns

Problem

I want to learn Design patterns with real time example. So can any one suggest where I can start.

Original source

Related problems