Design Mode in JDK

Source: Internet
Author: User
1. creational Patterns Creation Mode Abstract Factory (recognizeable by creational Methods returning the factory itself which in turn can be used to create another abstract/interface type)

Note that it is always # newinstance (). Generally, this is a static method that returns the factory object of a class. Then, this factory object can be used to create other abstract types. The final object to be created depends on the Implementation class of the abstract factory.

Create a group of associated object instances. This mode is also quite common in JDK, and there are many frameworks such as spring. We can easily find such an instance.

  • javax.xml.parsers.DocumentBuilderFactory#newInstance()
  • javax.xml.transform.TransformerFactory#newInstance()
  • javax.xml.xpath.XPathFactory#newInstance()
Builder (recognizeable by creational Methods returning the instance itself)

The returned object. It is mainly used to simplify the creation of a complex object.

  • java.lang.StringBuilder#append()(Unsynchronized)
  • java.lang.StringBuffer#append()(Synchronized)
  • java.nio.ByteBuffer#put()(Also onCharBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBufferAndDoubleBuffer)
  • javax.swing.GroupLayout.Group#addComponent()
  • All implementationsjava.lang.Appendable
Factory method (recognizeable by creational Methods returning an implementation of an abstract/interface type)

Simply put, return a type of instance as needed.

The following classes are all abstract classes, and the methods are static methods, that is, the static methods of these abstract classes can be used to return an instance. The instance type is the abstract type, specifically, it is implemented in static methods.

  • java.util.Calendar#getInstance()
  • java.util.ResourceBundle#getBundle()
  • java.text.NumberFormat#getInstance()
  • java.nio.charset.Charset#forName()
  • java.net.URLStreamHandlerFactory#createURLStreamHandler(String)(Returns singleton object per protocol)
Prototype (recognizeable by creational Methods returning DifferentInstance of itself with the same properties)

Use your own instance to create another instance. Sometimes, creating an instance and copying the value of an existing instance is a complex action. Therefore, this mode can avoid such complexity.

  • java.lang.Object#clone()(The class has to implementjava.lang.Cloneable)
Singleton (recognizeable by creational Methods returning SameInstance (usually of itself) everytime)

 

  • java.lang.Runtime#getRuntime()
  • java.awt.Desktop#getDesktop()

 

2. Structural Patterns structure mode adapter (recognizeable by creational methods taking an instance DifferentAbstract/interface type and returning an implementation of own/another abstract/interface type which Decorates/overridesThe given instance)
  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream)(ReturnsReader)
  • java.io.OutputStreamWriter(OutputStream)(ReturnsWriter)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal()And#unmarshal()
Bridge (recognizeable by creational methods taking an instance DifferentAbstract/interface type and returning an implementation of own abstract/interface type which Delegates/usesThe given instance)
  • None comes to mind yet. A fictive example wocould benew LinkedHashMap(LinkedHashSet<K>, List<V>)Which returns an unmodifiable linked map which doesn't clone the items,UsesThem.java.util.Collections#newSetFromMap()AndsingletonXXX()Methods however comes close.
Composite (recognizeable by behavioral methods taking an instance SameAbstract/interface type into a tree structure)
  • java.awt.Container#add(Component)(Practically all over swing thus)
  • javax.faces.component.UIComponent#getChildren()(Practically all over jsf ui thus)
Decorator (recognizeable by creational methods taking an instance SameAbstract/interface type which adds additional behaviour)
  • All subclassesjava.io.InputStream,OutputStream,ReaderAndWriterHave a constructor taking an instance of same type.
  • java.util.Collections,checkedXXX(),synchronizedXXX()AndunmodifiableXXX()Methods.
  • javax.servlet.http.HttpServletRequestWrapperAndHttpServletResponseWrapper
Facade (recognizeable by behavioral methods which internally uses instances DifferentIndependent abstract/interface types)
  • javax.faces.context.FacesContext, It internally uses among others the abstract/Interface TypesLifeCycle,ViewHandler,NavigationHandlerAnd more without that the enduser has to worry about it (which are however overrideable by injection ).
  • javax.faces.context.ExternalContext, Which internally usesServletContext,HttpSession,HttpServletRequest,HttpServletResponse, Etc.
Flyweight (recognizeable by creational Methods returning a cached instance, a bit the "multiton" idea)
  • java.lang.Integer#valueOf(int)(Also onBoolean,Byte,Character,ShortAndLong)
Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn Delegates/usesA DifferentImplementation of given abstract/interface type)
  • java.lang.reflect.Proxy
  • java.rmi.*, The whole API actually.

The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.

 

3. behavioral patterns behavior mode chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in AnotherImplementation SameAbstract/interface type in a queue)
  • java.util.logging.Logger#log()
  • javax.servlet.Filter#doFilter()
Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of DifferentAbstract/interface type which has been EncapsulatedBy the command implementation during its creation)

In command mode, requests are encapsulated into objects so that different requests, queues, or logs can be used to parameterize other objects. The command mode also supports unrecoverable operations.

The command mode can completely decouple the request sender and receiver. There is no direct connection between the sender and receiver. The sender only needs to know how to send the request command, and the rest can be ignored, you don't even need to worry about whether the command is successful or not. At the same time, we can easily add new commands, but it may be because the convenience and encapsulation of requests will cause too many specific command classes in the system.

  • All implementationsjava.lang.Runnable
  • All implementationsjavax.swing.Action
Interpreter (recognizeable by behavioral methods returning StructurallyDifferent instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

The interpreter mode defines the grammar of a language and creates an interpreter to explain sentences in the language. The interpreter mode describes how to construct a simple language interpreter. It is mainly used in compilers developed using object-oriented languages. It describes how to define a grammar for a simple language, how to represent a sentence in the language, and how to explain these sentences.

  • java.util.Pattern
  • java.text.Normalizer
  • All subclassesjava.text.Format
  • All subclassesjavax.el.ELResolver
Iterator (recognizeable by behavioral methods sequentially returning instances of DifferentType from a queue)

The so-called iterator mode provides a method to access each element in an aggregate object sequentially, rather than exposing its internal representation. In the iterator mode, the responsibility of the iteration element is handed over to the iterator instead of the aggregate object. We can implement the iteration of the aggregate object without knowing the internal structure of the aggregate object.

  • All implementationsjava.util.Iterator(Thus among others alsojava.util.Scanner!).
  • All implementationsjava.util.Enumeration
Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the Command pattern) which delegates/uses the given instance)

The so-called intermediary mode is to use an intermediary object to encapsulate a series of object interactions. The intermediary makes the objects do not need to be explicitly referenced to each other, so that their coupling is loose, in addition, the interaction between them can be changed independently.

Many pool technologies and middleware can be understood as the intermediary mode.

Timer is a thread that starts a thread for each timertask...

  • java.util.Timer(ALLscheduleXXX()Methods)
  • java.util.concurrent.Executor#execute()
  • java.util.concurrent.ExecutorService(invokeXXX()Andsubmit()Methods)
  • java.util.concurrent.ScheduledExecutorService(ALLscheduleXXX()Methods)
  • java.lang.reflect.Method#invoke()
Memento (recognizeable by behavioral methods which internally changes the state of WholeInstance)

The memorandum model is a kind of regret. It provides a mechanism for our software to restore the system to a specific historical state.

The memorandum mode captures the internal state of an object without damaging the encapsulation, and saves the State outside the object, so that the object can be restored to the previously saved State in the future.

  • java.util.Date(The setter methods do that,DateIs internally represented bylongValue)
  • All implementationsjava.io.Serializable
  • All implementationsjavax.faces.component.StateHolder
Observer (or publish/subscribe) (recognizeable by behavioral methods which invokes a method on an instance AnotherAbstract/interface type, depending on own state)

The observer mode defines the one-to-many dependency between objects. In this way, when an object changes its status, all its dependent persons will receive notifications and update them automatically.

  • java.util.Observer/java.util.Observable(Rarely used in real world though)
  • All implementationsjava.util.EventListener(Practically all over swing thus)
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener
  • javax.faces.event.PhaseListener
State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

In many cases, the behavior of an object depends on one or more of its changing attributes. These variable attributes are called states, that is, behavior dependent States, that is, when the status of the object changes due to external interaction, its behavior will also change accordingly. In this case, we cannot use behavior to control changes in the state. Instead, we should consider behavior from the State perspective, that is, what status should be done. This is the status mode.

Therefore, the State mode allows an object to change its behavior when its internal state changes. The object seems to have modified its class.

The lifecycle class must handle many different states in the lifecycle.

It changes its behavior by taking the state as an atom, instead of changing the State through the action.

  • javax.faces.lifecycle.LifeCycle#execute()(ControlledFacesServlet, The behaviour is dependent on current phase (State) of JSF lifecycle)
Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of DifferentAbstract/interface type which has been Passed-inAs method argument into the strategy implementation)

Therefore, the policy mode defines the algorithm family and encapsulates them separately so that they can convert each other. However, this mode is independent of the customers who use the algorithm.

  • java.util.Comparator#compare(), Executed by among othersCollections#sort().
  • javax.servlet.http.HttpServlet,service()And alldoXXX()Methods TakeHttpServletRequestAndHttpServletResponseAnd the implementor has to process them (and not to get hold of them as instance variables !).
  • javax.servlet.Filter#doFilter()
Template Method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)
  • All non-Abstract METHODSjava.io.InputStream,java.io.OutputStream,java.io.ReaderAndjava.io.Writer.
  • All non-Abstract METHODSjava.util.AbstractList,java.util.AbstractSetAndjava.util.AbstractMap.
  • javax.servlet.http.HttpServlet, AlldoXXX()Methods By default sends a HTTP 405 "method not allowed" error to the response. You're free to implement none or any of them.
Visitor (recognizeable by two DifferentAbstract/interface types which has methods definied which takes each OtherAbstract/interface type; the one actually callthe method of the other and the other executes the desired strategy on it)
  • javax.lang.model.element.AnnotationValueAndAnnotationValueVisitor
  • javax.lang.model.element.ElementAndElementVisitor
  • javax.lang.model.type.TypeMirrorAndTypeVisitor

 

Iv. Design Principles 1. Single responsibility principles

A class has only one reason for its change. There should be only one responsibility. Every responsibility is a changing axis. If a class has more than one responsibility, these responsibilities are coupled. This leads to a fragile design. When a responsibility changes, other responsibilities may be affected. In addition, coupling of multiple responsibilities will affect reusability. For example, you need to separate the logic from the interface. From: Baidu encyclopedia

2. Open Close Principle)

The principle of opening/closing is to sayOpen to extension and disable Modification. When the program needs to be expanded, you cannot modify the original code to achieve a hot swapping effect. So in a word, it is easy to maintain and upgrade the program to make it more scalable. To achieve this, we need to use interfaces and abstract classes. We will mention this in the specific design.

3. liskov substitution principle)

Liskov substitution principle LSP is one of the basic principles of object-oriented design. In the Rys replacement principle, subclasses can certainly appear where any base class can appear. LSP is the cornerstone of inheritance reuse. Only when the primary class can replace the base class and the functions of the software unit are not affected can the base class be reused, the category class can also add new behaviors based on the base class. The Li's replacement principle is a supplement to the "open-closed" principle. The key step for implementing the "open-close" principle is abstraction. The inheritance relationship between the base class and sub-classes is the specific implementation of abstraction. Therefore, the Li's replacement principle is the standard for the specific steps to implement abstraction. From: Baidu encyclopedia

4. Dependence inversion principle)

The dependence inversion principle is dependent on abstraction, not specific. Simply put, we need to program the abstraction rather than the implementation, which reduces the coupling between the customer and the implementation module.

The key to achieving the principle of open/closed is abstraction, and specific implementation is exported from abstraction. If the principle of open/closed is the goal of object-oriented design, the principle of dependency reversal is the main means of object-oriented design. From: Baidu encyclopedia

5. Interface segregation principle)

This principle means that using multiple isolated interfaces is better than using a single interface. We can see from this that the design mode is a software design idea, starting from the large-scale software architecture, for the convenience of upgrading and maintenance. So it appears many times above: reducing dependencies and reducing coupling.

6. Composite Reuse Principle)

The principle of merging and reusing is to use existing objects in a new object through associations (including composite and aggregation relationships) to make them part of the new object; new objects reuse their existing functions by calling existing methods by Delegate. To put it simply, use combination/aggregation as much as possible, and use less inheritance.

7. Demeter Principle)

What is the principle of least understanding? That is to say, an entity should interact with other entities as little as possible so that the system function modules are relatively independent. That is to say, a software entity should interact with other entities as little as possible. In this way, when a module is modified, it will affect other modules as little as possible, and expansion will be relatively easy, which is a limitation on communication between software entities, it requires limiting the width and depth of communication between software entities.

 

 

Refer:

Examples of gof design patterns summary design patterns Reading Notes ----- command patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.