thil
thil

Reputation: 75

Design patterns with real time example

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

Upvotes: 4

Views: 33034

Answers (4)

Premraj
Premraj

Reputation: 74581

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

Upvotes: 32

Pubudu Dodangoda
Pubudu Dodangoda

Reputation: 2874

Now here is an answer which would attract a lot of downvotes. But I'll tell it any way.

My suggestion is, "Don't learn design patterns!!!"

By sticking into design patterns, you restrict your creativity. Also, some design patterns have bad sides, which they don't tell you. For example, the Singleton pattern can cause issues if not used with care.

Also, IMO, some famous design patterns were created with one language in mind, to solve a particular issue with that language. However, evolved languages like Python and Javascript can be used pretty amazingly without sticking into design patterns.

Instead of learning design patterns, learn programming paradigms, and the internal concepts. I'll copy paste the following list from Wikipedia,

  • imperative which allows side effects,
  • functional which disallows side effects,
  • declarative which does not state the order in which operations execute,
  • object-oriented which groups code together with the state the code modifies,
  • procedural which groups code into functions,
  • logic which has a particular style of execution model coupled to a particular style of syntax and grammar, and
  • symbolic programming which has a particular style of syntax and grammar

Of course you can read through the standards design patterns to get some basic idea. But don't learn them from A to Z. It can destroy your creativity.

Upvotes: 1

Sujit Prabhakaran
Sujit Prabhakaran

Reputation: 343

If you are looking for C# design patterns then refer:

'C# Design Patters a tutorial' - Jame W Cooper

Upvotes: 0

jahroy
jahroy

Reputation: 22692

I believe these are the two standard references:

  1. Head First Design Patterns
  2. Design Patterns

From what I've heard, the first is easier to start with.

The steps I took to investigate this:

  1. google "design pattern books"
  2. read this question

Upvotes: 2

Related Questions