Introduction to "Java Fundamentals" Java Design Patterns

Source: Internet
Author: User

What is design pattern design pattern is a set of reusable, widely known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. Design pattern is not a method and technology, but a kind of thought design pattern, and the specific language is irrelevant, but this article is explained by the Java as the Language Foundation, the learning design pattern is to establish the object-oriented thought, as far as possible the interface programming, the low coupling, cohesion, makes the design procedure reusable. Design patterns can be summed up in the following categories: • Create pattern: Object Creation • Structured mode: Object composition (structure) and behavioral pattern: The behavior of the object describes some simple common design patterns, respectively. Singleton mode (Singleton pattern)

Singleton mode is a kind of common software design pattern. In its core structure, there is only one special class that is called a singleton. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system. The following is a sample design for a singleton pattern:

 PackageCn.pattern;/*** Created by Lili on 15/12/14. Double lock Type*/ Public classSingletonclass {//Global Singleton object instance, in order to prevent external changes instance, will instance private, does not support external assignment and access//Static modification is because the externally exposed method is static, so accessing the external member variable in a static method must also be static.    Private StaticSingletonclass instance =NULL; //The construction method is privatized to prevent the outside world from arbitrarily creating objects, so that this class can only be built internally    PrivateSingletonclass () {}//you do not need to create an object to access it, you must set the method to static//      Public StaticSingletonclass getinstance () {if(Instance = =NULL) {            //It is only possible to create objects here, so in order to prevent concurrent creation of multiple objects , a synchronous code block is taken            synchronized(Singletonclass.class) {                if(Instance = =NULL) {instance=NewSingletonclass (); }            }        }        returninstance; }}

The above-mentioned wording is double-locked, and there are two other ways of writing, namely, lazy and a hungry man:

/*** Lazy-type, only when the call to get the instance method to start creating objects, more lazy*/ Public classSingletonclass {Private StaticSingletonclass instance =NULL; PrivateSingletonclass () {} Public Static synchronizedSingletonclass getinstance () {if(Instance = =NULL) {instance=NewSingletonclass (); }        returninstance; }}
 /**   * a hungry man-type, class-loaded when it was created, very hungry  */ public  class   Singletonclass { private  static  final     Singletonclass instance = new   Singletonclass ();  private   Singletonclass () {}  Span style= "color: #0000ff;" >public  static   Singletonclass    GetInstance () { return   instance; }}

in the specific development of multi-use a hungry man , such as the JDK runtime is the A hungry man-style design.

Simple Factory mode

The simple factory pattern is a creation mode, also called the Static Factory method (static Factory methods) mode, the simple factory pattern is determined by a factory object to create an instance of which product class. The essence of the simple factory model is that a factory class dynamically determines which product class (these product classes inherit from a parent class or interface) should be created, based on the parameters passed in. The advantage of this simple model is that the outside world avoids the awkward work of creating objects, and only consumes them. But all the creation logic of this model is in the factory class, violates the principle of high cohesion, and when the product class is many, the judgment logic will be complicated with the judgment of the product type, which is not conducive to maintenance and expansion.

The following example is an example of a simple factory, animal is an abstract interface for product objects, and dog and cat are specific products, and the factory provides static methods for external invocation, which returns different product objects based on the different parameters passed in from outside.

 Public classAnimalfactory {Privateanimalfactory () {} Public StaticAnimal createanimal (String type) {if("Dog". Equals (Type) {            return NewDog (); } Else if("Cat". Equals (Type) {            return NewCat (); } Else {            return NULL; }    }}

Factory method Mode

Factory method Mode (FACTORY approach) is a common object creation design pattern, the core spirit of this mode is the invariant part of the encapsulation class, extracting the individual changeable part as the independent class, through the dependency injection to achieve the decoupling, reuse and convenient later maintenance extension purposes, This partly solves the drawbacks of the simple factory model. The core structure of the factory method model has four roles, namely abstract factory, concrete factory, abstract product, concrete product.

The factory method model abstracts the Simple factory model. There is an abstract factory class (which can be abstract classes and interfaces), and this class will no longer be responsible for the production of specific products, but only to formulate some specifications, specific production work by its subclasses to complete. In this mode, the factory class and the product class can often correspond in turn. That is, an abstract factory corresponding to an abstract product, a specific factory corresponding to a specific product, this specific factory is responsible for the production of the corresponding products.

Here's a simple example to illustrate:

Abstract factory, only responsible for defining specifications, specific production sub-class completion.

 Public Interface Factory {    publicabstract  Animal createanimal ();}

Specific factories, each product corresponds to a specific factory, as if the production line, but each product line has a number of plant characteristics, such as the production of products.

 Public class Implements Factory {    @Override    public  Animal createanimal () {        returnNew  Cat ();    }}
 Public class Implements Factory {    @Override    public  Animal createanimal () {        return  New  Dog ();}    }

Finally, when we use, we call different specific factories to produce the corresponding products.

 Public class Animaldemo {    publicstaticvoid  main (string[] args) {        new  dogfactory ();         = f.createanimal ();        A.eat ();                 New catfactory ();         = f.createanimal ();        A.eat ();    }}

Introduction to "Java Fundamentals" Java Design 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.