Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
thil Avatar asked Jul 19 '12 04:07

thil


People also ask

What are design patterns explain with example?

Design patterns provide a standard terminology and are specific to particular scenario. For example, a singleton design pattern signifies use of single object so all developers familiar with single design pattern will make use of single object and they can tell each other that program is following a singleton pattern.

When we use Singleton design pattern give real time example?

If in your solution some object has only one instance and you want to model that in your design then you should use singleton pattern. For example if you are modelling a PC in the software there can be only one instance of a PC with respect to your running program.

What are the 3 types of patterns?

Three Types of Design Patterns (Behavioral, Creational, Structural) Distinguish between Behavioral, Creational, and Structural Design Patterns.

What is the most used design pattern?

One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic. The only problem with a factory method is it relies on the concrete component.


1 Answers

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.

Prototype : A fully initialized instance to be copied or cloned
Example : initial status of chess game

  • 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 : when we make (or order) a pizza(it can de deferent in size and flavours )

  • 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

This design patterns is all about Class and Object composition i.e. How do you want structure the software component. This helps us guarantee that when one of the parts changes, the entire structure does not need to change.

Proxy - An object representing another object.
Example : check book leaf, credit card, debit card are proxy for Money and a customer representative to order a product.

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

Composite - Gives an unified interface to a leaf and composite.
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 - Gives additional feature to objects, while giving unified interface.
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 - Single interface that represents entire subsystem.
Example : Control Panel, Event Manager.

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

Adapter - Provides different interfaces for an interface.
Example : Power Adapters

  • java.util.Arrays#asList()

Flyweight - A fine-grained instance used for efficient sharing
Example : The Flyweight uses sharing to support large numbers of objects efficienthttps://refactoring.guru/design-patternsly. The public switched telephone network is an example of a Flyweight. There are several resources such as dial tone generators, ringing generators, and digit receivers that must be shared between all subscribers. A subscriber is unaware of how many resources are in the pool when he or she lifts the handset to make a call. All that matters to subscribers is that a dial tone is provided, digits are received, and the call is completed.

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

Behavioral

This design patterns specially concerned with communication between Objects.

Chain of Responsibility - A way of passing a request between a chain of objects
Example : Loan or Leave approval process, Exception handling in Java.

  • javax.servlet.Filter#doFilter()

Iterator - Sequentially access the elements of a collection
Example : Next/Previous buttons on TV

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

State - Alter an object's behaviour when its state changes
Example : A fan wall control

Observer - A way of notifying change to a number of classes
Example : Bidding or auction

  • Publish/Subscribe JMS API

Visitor - Defines a new operation to a class without change. Example : Taxi

Template - Defines a skeleton of an algorithm in an operation, and defers some steps to subclasses.
Example : A blue print

  • 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 - Encapsulate a command request as an object
Example : The "Guest Check" at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by each waiter is not dependent on the menu, and therefore they can support commands to cook many different items.

  • All implementations of java.lang.Runnable

Memento - Capture and restore an object's internal state
Example : save the state in a game & Undo/Redo operation in Windows

  • All implementations of java.io.Serializable

Mediator - Defines simplified communication between classes
Example : Air Traffic Controller(ATC)

Strategy - A Strategy defines a set of algorithms that can be used interchangeably.
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

like image 59
Premraj Avatar answered Sep 30 '22 17:09

Premraj