Java Design Pattern Learning

Source: Internet
Author: User

Design mode (Patterns)

--the basis of reusable object-oriented software

Design patterns are a set of reusable, most 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. There is no doubt that design patterns in others in the system are multi-win, design patterns so that code is truly engineering, design patterns are the cornerstone of software engineering, like a block of bricks and tiles in the building. The rational use of design patterns in the project can solve many problems perfectly, each of which has corresponding principles in the present, each of which describes a recurring problem around us, and the core solution of the problem, which is why it can be widely used. This chapter is the beauty of Java [from rookie to master evolution] series of design patterns, we will be a combination of theory and practice in this chapter of the study, hope that the vast number of process enthusiasts, learn the design model, do a good software engineer!

I. Classification of design Patterns

In general, design patterns fall into three broad categories:

Create five types of models: Factory method mode, abstract Factory mode, singleton mode, builder mode, prototype mode.

Structure mode, a total of seven kinds: Adapter mode, adorner mode, proxy mode, appearance mode, bridging mode, combined mode, enjoy the meta-mode.

There are 11 types of behavioral Patterns: Strategy mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, mediator mode, interpreter mode.

In fact, there are two types: concurrency mode and thread pool mode.

The six principles of design pattern

1. Opening and closing principle (Open Close Principle)

The open and closed principle is to say to the expansion opening, to modify the closure . When the program needs to expand, can not modify the original code, to achieve a hot plug effect. So a nutshell is: In order to make the program good extensibility, easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes, which we will refer to later in the specific design.

2. The principle of substitution on the Richter scale (Liskov Substitution Principle)

One of the fundamental principles of object-oriented design of the Richter substitution principle (Liskov Substitution Principle LSP). The Richter substitution principle says that where any base class can appear, subclasses must be able to appear. LSP is the cornerstone of inheritance reuse, only if the derived class can replace the base class, the function of the Software unit is not affected, the base class can be really reused, and the derived class can also add new behavior on the basis of the base class. The principle of substitution on the Richter scale is a supplement to the principle of "open-closed". The key step in implementing the "open-close" principle is abstraction. The inheritance of the base class and subclass is the concrete implementation of abstraction, so the principle of the substitution of the Richter scale is the specification of the concrete steps to realize the abstraction. --from Baidu Encyclopedia

3. Dependence reversal principle (dependence inversion Principle)

This is the basis of the open and close principle, the specific content: TRUE interface programming, relying on abstraction and not dependent on the specific.

4. Interface Isolation principle (Interface segregation Principle)

This principle means that using multiple isolated interfaces is better than using a single interface. or a reduction of the coupling between the class meaning, from here we see, in fact, the design pattern is a software design ideas, from the large software architecture, in order to upgrade and maintenance convenience. So there are multiple occurrences: reducing dependency and reducing coupling.

5, Dimitri Law (least known principle) (Demeter Principle)

Why is it called the least known principle, that is to say: an entity should be as small as possible interaction with other entities, so that the system function module is relatively independent.

6. Synthetic multiplexing principles (Composite reuse Principle)

The principle is to use composition/aggregation as much as possible, rather than using inheritance.

Above reference http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html

Three, Factory mode, abstract Factory mode, single case mode

1. Factory mode     

Abstract interface for entity classes

Public interface Sender {


public void Send ();
}

Implementation of an entity class

public class MailSender implements Sender {

@Override
public void Send () {

System.out.println ("This is mailsender!");
}

}

Entity class implementation Two

public class Smssender implements Sender {

@Override
public void Send () {
System.out.println ("This is SMS sender!");

}

}

Factory entity Class

public class Sendfactory {

Public Sender Produce (String type) {

if ("Mail". Equals (type)) {

return new MailSender ();
} else if ("SMS". Equals (type)) {

return new Smssender ();
}else{
System.out.println ("Please enter the correct type!") ");
return null;

}



}

Factory Test class

public class Factorytest {

public static void Main (string[] args) {

Sendfactory factory = new Sendfactory ();
Sender sender = Factory.produce ("ss");
Sender. Send ();

}

}

second, abstract factory

In the example above, the factory class is created as an abstract factory, which corresponds to the corresponding entity class when the factory is implemented. This allows the extension to be implemented without modifying the original code and corresponding to the closure principle.

In providing an interface:

 
    1. Public interface Provider {
    2. Public Sender produce ();
    3. }

Two factory classes:

 
    1. public class Sendmailfactory implements Provider {
    2. @Override
    3. Public Sender Produce () {
    4. return new MailSender ();
    5. }
    6. }
 
    1. public class Sendsmsfactory implements provider{
    2. @Override
    3. Public Sender Produce () {
    4. return new Smssender ();
    5. }
    6. }

Test class:

 

public class Test {

public static void Main (string[] args) {

Provider Provider = new Sendmailfactory ();

Sender sender = Provider.produce ();

Sender. Send ();

}

}

Four, single case mode

Thread-Safe Single-instance mode implementation There are several ideas, personally think the 2nd kind of scheme is the most elegant:, a hungry man-type, with the help of internal class, Ordinary locking solution, double detection, but to note the wording, if the monomer mode continues to expand to n-ary monomer mode, that is the object pool mode

1. A hungry man type single case


public class Singleton {
Private final static Singleton INSTANCE = new Singleton ();

Private Singleton () {}

public static Singleton getinstance () {
return INSTANCE;
}
}

2, the use of internal class
is a lazy singleton, because the Java mechanism stipulates that the inner class Singletonholder is loaded (and lazy) only when the getinstance () method is first called, and its loading process is thread-safe. An instance is instantiated once when the inner class is loaded.


public class Singleton {

Private Singleton () {}

private Static Class Singletonholder {
Private final static Singleton INSTANCE = new Singleton ();
}

public static Singleton getinstance () {
return singletonholder.instance;
}
}

3, Ordinary lock solution


public class Singleton {
private static Singleton instance = NULL;

Private Singleton () {}

public static synchronized Singleton getinstance () {
if (instance = = null) {
Instance = new Singleton ();
}

return instance;
}
}

Although thread safety is resolved, but each thread calls getinstance to lock, we want to lock only when the first call to GetInstance, see the following double detection scheme

4, double detection, but pay attention to the wording


public class Singleton {
private static Singleton instance = NULL;

Private Singleton () {}

public static Singleton getinstance () {
if (instance = = null) {
Synchronzied (Singleton.class) {
Singleton temp = instance;
if (temp = = null) {
temp = new Singleton ();
Instance = Temp
}
}
}

return instance;
}
}

Because of the order reordering problem, it is not possible to write directly as follows:
public class Singleton {
private static Singleton instance = NULL;

Private Singleton () {}

public static Singleton getinstance () {
if (instance = = null) {
Synchronzied (Singleton.class) {
if (instance = = null) {
Instance = new Singleton ();
}
}
}

return instance;
}
}

However, if the instance instance variable is modified with a volatile modifier, the volatile modifier will ensure that instance = new Singleton (), the corresponding instruction is not reordered, and the following code is thread-safe:
public class Singleton {
Private static volatile Singleton instance = null;

Private Singleton () {}

public static Singleton getinstance () {
if (instance = = null) {
Synchronzied (Singleton.class) {
if (instance = = null) {
Instance = new Singleton ();
}
}
}

return instance;
}
}

Java Design Pattern Learning

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.