Taking Notes on Design Pattern

Taking Notes on Design Pattern

What is Design Patterns?
Design pattern describes a problem which occurs over and over again, and then describes the core of the solution to that problem.
Design patterns are a well-established mechanism for communicating best practices.
Why use Design Patterns?
Reuse solutions
Most problems we encounter as programmers have been handled time and again by others. Design patterns can provide us with the means to reuse their solution and wisdom.
We also learn from the experience of others enriches our language.
Establish a common base of vocabulary and terminology
Communication and teamwork require a common base of vocabulary and a common viewpoint of the problem. Design patterns provide a common point of reference during the analysis and design phase of a project.
Design patterns give a higher perspective on analysis and design
Patterns give you a higher-level perspective on the problem and on the process of design and object orientation.
This frees you from the tyranny of dealing with the details too early.
Design patterns helped both individual learning and team communications and development.
Creational Patterns
Factory pattern
It is used to take the rules of how to perform the instantiation out of the client object that is using these created objects.
Factory Method Pattern
Definition:
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.
Participants
Product, ConcreteProduct, Factory, ConcreteFactory
Factory relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Abstract Factory Pattern
Definition:
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
The Abstract Factory is used when we must coordinate the creation of families of objects and each family is used under different circumstances.
The AbstractFactory defines the interface for how to create each member of the family of objects required.
We implement one concrete factory class for each family.
To create different types of product objects, clients should use a different concrete factory.
Consequences
A factory is responsible for creating product objects; it isolates clients from the task of creating product objects.
2. It makes exchanging product families easy.
3.  It promotes consistency among products. When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time.
AbstractFactory makes this easy to enforce.  
4. Supporting new kinds of products is difficult, as this requires extending the factory interface and changing the AbstractFactory class and all of its subclasses.
Builder Pattern
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Applicability
Use the Builder pattern when
  the algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.  
  the construction process must allow different representations for the object that's constructed.  
Consequences
1. It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product.
2. It isolates code for construction and representation. The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented.
3. It gives you finer control over the construction process. The Builder pattern constructs the product step by step under the director's control. This gives you finer control over the construction process and consequently the internal structure of the resulting product.
STRUCTURAL PATTERNS
Decorator
The Decorator Pattern is used to extend the functionality of an object dynamically without having to change the original class source or using inheritance. The key to a decorator is that a decorator "wraps" the object decorated and looks to a client exactly the same as the object wrapped. This means that the decorator implements the same interface as the object it decorates.
Participants
•Component - defines the interface for objects that can have responsibilities added to them dynamically.  
•ConcreteComponent - defines an object to which additional responsibilities can be attached.
•Decorator - maintains a reference to a Component object and defines an interface that conforms to Component's interface.
•ConcreteDecorator - adds responsibilities to the component. 
Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request. 
Decorator also implements Component interface, it can be treated as component, a decorator object can contain another decorator object and can forward calls to it. In this way, new decorators, and hence new functionality, can be built by wrapping an existing decorator object.
Benefits
More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to objects than can be had with static inheritance. With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility.
It is easy to add new component, and new decorator.
It is easy to add any combination of capabilities. The same capability can even be added twice.
I can prevent the proliferation of subclasses leading to less complexity and confusion.
Liabilities
Lots of little objects. A design that uses Decorator often results in systems composed of lots of little objects that all look alike.
Although these systems are easy to design, customize and extend, they can be hard to learn, use and debug.
Examples 1:
VisualComponent
TextView
Decorator
ScrollDecorator and BorderDecorator
Examples 2:
Logger
ConsoleLogger, FileLogger
LoggerDecorator
EncryptLogger
Decorator Pattern in java.io
InputStream, OutputStream(Byte)
Reader, Writer (Char)
Binary I/O streams (ascii, 8 bits)
InputStream
OutputStream
• Character I/O streams (Unicode, 16 bits)
Reader
Writer
Java filter streams (decorators) are added dynamically to create the functionality needed.
Input decorator: FilterInputStream
Output decorator: FilterOutputStream
InputStream Hierarchy
• Abstract component root in decorator pattern - InputStream
• Concrete components
FileInputStream, ByteArrayInputStream, StringBufferInputStream, PipedInputStream
• Abstract decorator - FilterInputStream
• Concrete decorators
DataInputStream, BufferedInputStream, LineNumberInputStream, PushbackInputStream, etc.
DataInputStream in = new DataInputStream(new BufferedInputStream (new FileInputStream("invoice1.txt")));
OutputStream Hierarchy
• Abstract component root in decorator pattern – OutputStream
• Concrete components
FileOutputStream, ByteArrayOutputStream, PipedOutputStream
• Abstract decorator –FilterOutputStream
• Concrete decorators
DataOutputStream,PrintStream, BufferedOutputStream
DataOutputStream out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream("invoice1.txt")));
Reader and Writer Classes
Internationalization Unicode support
Structured in class hierarchies similar to the InputStream and OutputStream hierarchies
Reader Class Hierarchy
• Abstract component root in decorator pattern –Reader
• Concrete components – BufferedReader
• Abstract decorator –FilterReader
• Concrete decorators – PushbackReader
ADAPTER Pattern
Adapter pattern can convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Sometimes, an existing class may provide the functionality required by a client, but its interface may not be what the client expects. In such cases, to reuse the existing class, the existing interface needs to be converted into another interface, which the client expects.
The Adapter pattern suggests defining a wrapper class around the object with the incompatible interface. This wrapper object is referred as an adapter and the object it wraps is referred to as an adaptee. The adapter provides the required interface expected by the client. The implementation of the adapter interface converts client requests into calls to the adaptee class interface.
Applicability
Use the Adapter pattern when you want to use an existing class, and its interface does not match the one you need.  
CLASS ADAPTERS VERSUS OBJECT ADAPTERS
Adapters can be classified broadly into two categories - class adapters and object adapters - based on the way a given adapter is designed.
Class Adapter
A class adapter is designed by sub classing the adaptee class. In addition, a class adapter implements the interface expected by the client object. When a client object invokes a class adapter method, the adapter internally calls an adaptee method that it inherited.
Object Adapter
An object adapter contains a reference to an adaptee object. Similar to a class adapter, an object adapter also implements the interface, which the client expects.
When a client object calls an object adapter method, the object adapter invokes an appropriate method on the adaptee instance whose reference it contains.
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that carry out the request.
Adapter can only change the names of operations, or support an entirely different set of operations. The amount of work Adapter does depends on how similar the Target interface is to Adaptee's. 
Example:
AddressValidator{isValidAddress}
CAAddressValidator{isValidCanadianAddr}
Iteration to Enumeration
Enumeration to Iteration
Adapter Pattern in Java IO
ByteArrayInputStream, encapsulate array, and convert it to InputStream.
FileInputStream(FileDescriptor to InputStream)
StringBufferInputStream(String to InputStream)
ByteArrayOutputStream, FileOutputStream
CharArrayReader, StringReader,
CharArrayWriter, StringWriter
Byte to Char
InputStreamReader
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
Convert InputStream to Reader
OutputStreamWriter
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File("a.txt")));
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
Observer Pattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The key objects in this pattern are subject and observer.
A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject's state.
This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.
After applying the Observer pattern, different observers can be added dynamically without requiring any changes to the Subject class.
Applicability
Use the Observer pattern in any of the following situations:
• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
• When a change to one object requires changing others, and you don't know how many objects need to be changed.  
• When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.  
Participants
• Subject - knows its observers. Any number of Observer objects may observe a subject, provides an interface for attaching and detaching Observer objects.  
• Observer - defines an updating interface for objects that should be notified of changes in a subject.
• ConcreteSubject - stores state of interest to ConcreteObserver objects, sends a notification to its observers when its state changes.
• ConcreteObserver - maintains a reference to a ConcreteSubject object, stores state that should stay consistent with the subject's, implements the Observer updating interface to keep its state consistent with the subject's.
Collaborations
• ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.  
• After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.
Consequences
1. Abstract coupling between Subject and Observer. All a subject knows is that it has a list of observers, each conforming to the simple interface of the abstract Observer class. The subject doesn't know the concrete class of any observer. Thus the coupling between subjects and observers is abstract and minimal.   
2. Support for broadcast communication.
The notification is broadcast automatically to all interested objects that subscribed to it.
3. Unexpected updates.
Observer in Java
Interface: Observer
Observable Class - setChaged, and notifyObservers methods.
Remember to call setChaged() method before notifyObservers, otherwise, will not notify changes to observers.
Example:
IndexPaser, PackageParser, ClassPaser.
Command Pattern
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Command pattern turns the request itself into an object. This object can be stored and passed around like other objects.
Applicability
• Specify, queue, and execute requests at different times.
• Support undo.
Participants
• Command - declares an interface for executing an operation.
• ConcreteCommand - defines a binding between a Receiver object and an action, implements Execute by invoking the corresponding operation(s) on Receiver.
• Client - creates a ConcreteCommand object and sets its receiver.
• Invoker - asks the command to carry out the request.  
• Receiver - knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.  
Consequences
The Command pattern has the following consequences:
1. Command decouples the object that invokes the operation from the one that knows how to perform it.
2. Commands are first-class objects. They can be manipulated and extended like any other object.
3. You can assemble commands into a composite command.
4. It’s easy to add new Commands.
Example:
PlayBox, Keypad,
Command, Start/Stop/PlayCommand
MacroCommand
Behavioral Patterns
Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
The request gets passed along a chain of objects until one of them handles it.
It decouples an object that sends out a request and the set of potential request handler objects.
Applicability
Use Chain of Responsibility when
• More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.  
• You want to issue a request to one of several objects without specifying the receiver explicitly.  
• The set of objects that can handle a request should be specified dynamically.
Consequences
1.  Reduced coupling
2.  Added flexibility in assigning responsibilities to objects.
3.  Receipt isn't guaranteed.
Example:
PurchaseRequest
PRHandler
BranchManager,RegionalDirector,PresidentCOO,VicePresident
Event Mode in DHTML
Java web Filter
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Participants
•  Strategy - declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
•  ConcreteStrategy - implements the algorithm using the Strategy interface.
•  Context - is configured with a ConcreteStrategy object, maintains a reference to a Strategy object, may define an interface that lets Strategy access its data.
Consequences
The Strategy pattern has the following benefits and drawbacks:
1.  Families of related algorithms.
3.  Strategies eliminate conditional statements.
Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
A template method defines an algorithm in terms of abstract operations that subclasses must override to provide concrete behavior.
Applicability
The Template Method pattern should be used
• To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
• When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.
Template methods are a fundamental technique for code reuse.
Example:
Reporter.generateReport
HTMLRepoter/ClassHTLReporter
Visitor Pattern
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Applicability
Use the Visitor pattern when
• An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.  
• Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.  
Participants
• Visitor (visit) - declares a Visit operation for each class of ConcreteElement in the object structure.
•  Concrete Visitor (TypeCheckingVisitor)
•  Element (accept) - defines an Accept operation that takes a visitor as an argument.
•  ConcreteElement (AssignmentNode,VariableRefNode) - implements an Accept operation that takes a visitor as an argument.
•  ObjectStructure (Program) - can enumerate its elements, may provide a high-level interface to allow the visitor to visit its elements,  may either be a composite (see Composite (163)) or a collection such as a list or a set.  
Consequences
1.  Visitor makes adding new operations easy.
2.  A visitor gathers related operations and separates unrelated ones
3.  Adding new ConcreteElement classes is hard. The Visitor pattern makes it hard to add new subclasses of Element
4.  Visiting across class hierarchies, it can visit objects that don't have a common parent class. You can add any type of object to a Visitor interface.
Accumulating state.
Breaking encapsulation.
Example 1:
Element/ElementA/CompositeElement
Visitor/ConcreteVisitor
Example 2:
Visitor/PriceVisitor/InventoryVisitor(visitHardDisk, visitCPU...)
Equipment/HardDisk/CPU(accept)
Iterator Pattern
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The Iterator pattern allows a client object to access the contents of a container in a sequential manner, without having any knowledge about the internal representation of its contents.
The Iterator class defines an interface for accessing the list's elements. An iterator object is responsible for keeping track of the current element.
Separating the traversal mechanism from the List object lets us define iterators for different traversal policies without enumerating them in the List interface
The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object.
Applicability
Use the Iterator pattern
•  to access an aggregate object's contents without exposing its internal representation. 
•  to support multiple traversals of aggregate objects.
•  to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).  
Participants
•  Iterator - defines an interface for accessing and traversing elements.
•  ConcreteIterator - implements the Iterator interface, keeps track of the current position in the traversal of the aggregate. 
•  Aggregate - defines an interface for creating an Iterator object.  
•  ConcreteAggregate - implements the Iterator creation interface to return an instance of the proper ConcreteIterator.  
1.  It supports variations in the traversal of an aggregate.
2.  Iterators simplify the Aggregate interface.
3.  More than one traversal can be pending on an aggregate.
1.  Who controls the iteration?
When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator.
Internal iterators
– The collection itself offers methods to allow a client to visit different objects within the collection. For example, the java.util.Result-Set
– There can be only one iterator on a collection at any given time.
– The collection has to maintain or save the state of iteration.
External iterators
– The iteration functionality is separated from the collection and kept inside a different object referred to as an  iterator. Usually, the collection itself returns an appropriate iterator object to the client depending on the client input.
– There can be multiple iterators on a given collection at any given time.
Usage in Java
Enumeration
Iterator/ListIterator[add,remove,set,previous,next]
AbstractList, Inner class, Itr,ListItr
Fail fast, ConcurrentModificationException

Resources:
Post a Comment

Labels

Java (159) Lucene-Solr (110) All (60) Interview (59) J2SE (53) Algorithm (37) Eclipse (35) Soft Skills (35) Code Example (31) Linux (26) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Continuous Integration (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Design (8) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Miscs (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Firefox (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Bit Operation (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts