Five typical creation modes of Java design patterns (with examples and details) and java Design Patterns

Source: Internet
Author: User

Five typical creation modes of Java design patterns (with examples and details) and java Design Patterns
I. Overview

In general, the design model is divided into three categories:

(1) Creation modes:Factory method mode, abstract factory mode, Singleton mode, builder mode, and prototype mode.

(2) There are seven structural modes:Adapter mode, decorator mode, proxy mode, appearance mode, bridging mode, combination mode, and metadata mode.

(3) 11 behavior models:Rule mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, command mode, memorandum mode, state mode, visitor mode, intermediary mode, interpreter mode.

Ii. six principles of the design model

1. Open Close Principle)

The principle of opening/closing is to open the extension and disable the modification. When the program needs to be expanded, you cannot modify the original code to achieve a hot swapping effect.

2. Liskov Substitution Principle)

Its official description is abstract and can be Baidu. In fact, it can be understood as follows: (1) the Sub-class's ability must be greater than or equal to the parent class, that is, the methods that can be used by the parent class can be used by the sub-class. (2) The same is true for returned values. Assume that a parent class method returns a List, and the subclass returns an ArrayList. If the parent class method returns an ArrayList, And the subclass returns a List, it will be disconnected. Here, the sub-class return value is smaller than the parent class. (3) exceptions are thrown. Any subclass method can declare the subclass that throws the parent class method declaration exception.
The parent class does not have an declared exception.

3. Dependence Inversion Principle)

This is the basis of the open/closed principle. The specific content is interface-oriented programming, which relies on abstraction and not on specifics.

4. 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.

5. 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.

6. Composite Reuse Principle)

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

Iii. Creation Mode

Creation Mode:Factory method mode, abstract factory mode, Singleton mode, builder mode, and prototype mode.

3.1 factory method model

There are three factory method modes: Common factory mode, multiple factory method modes, and static factory method modes.

3.1.1 General factory Model

The common factory mode is to create a factory class and create instances for some classes that implement the same interface.

 

Package com. mode. create;


Public interface MyInterface {

Public void print ();

}

 

 

Package com. mode. create;


Public class MyClassOne implements MyInterface {


@ Override

Public void print (){

System. out. println ("MyClassOne ");

}


}

 

 

Package com. mode. create;


Public class MyClassTwo implements MyInterface {


@ Override

Public void print (){

System. out. println ("MyClassTwo ");

}


}

 

 

Package com. mode. create;


Public class MyFactory {


Public MyInterface produce (String type ){

If ("One". equals (type )){

Return new MyClassOne ();

} Else if ("Two". equals (type )){

Return new MyClassTwo ();

} Else {

System. out. println ("No type to be found ");

Return null;

}

}


}

 

 

Package com. mode. create;


Public class FactoryTest {


Public static void main (String [] args ){

MyFactory factory = new MyFactory ();

MyInterface myi = factory. produce ("One ");

Myi. print ();

}


}

The running result of FactoryTest should be obvious to me.

Let's look back to this sentence: the common factory mode is to create a factory class and create instances for some classes that implement the same interface.

3.1.2 multiple factory method Modes

Multiple factory method modes improve the common factory method mode. Multiple factory method modes provide multiple factory methods to create objects respectively.

Let's look at the code. Modify MyFactory and FactoryTest as follows:

 

Package com. mode. create;


Public class MyFactory {


Public MyInterface produceOne (){

Return new MyClassOne ();

}


Public MyInterface produceTwo (){

Return new MyClassTwo ();

}


}

 

 

Package com. mode. create;


Public class FactoryTest {


Public static void main (String [] args ){

MyFactory factory = new MyFactory ();

MyInterface myi = factory. produceOne ();

Myi. print ();

}


}

The running result is also very obvious.

Let's look back to this sentence: Multiple factory method modes improve the common factory method mode. Multiple factory method modes provide multiple factory methods to create objects respectively.

3.1.3 static factory method mode

The static factory method mode sets the methods in the above multiple factory method modes to static. You can directly call the method without creating an instance.

Let's look at the code. Modify MyFactory and FactoryTest as follows:

 

Package com. mode. create;


Public class MyFactory {


Public static MyInterface produceOne (){

Return new MyClassOne ();

}


Public static MyInterface produceTwo (){

Return new MyClassTwo ();

}


}

 

 

Package com. mode. create;


Public class FactoryTest {


Public static void main (String [] args ){

MyInterface myi = MyFactory. produceOne ();

Myi. print ();

}


}

The running result is still obvious.

Review: The static factory method mode sets the methods in the above multiple factory method modes to static. You can directly call the method without creating an instance.

3.2 Abstract Factory Model

One problem with the factory method mode is that the creation of the class depends on the factory class. That is to say, if you want to expand the program, you must modify the factory class, which violates the closure principle.

To solve this problem, let's take a look at the abstract factory mode: create multiple factory classes, so that once new functions need to be added, we can simply add new factory classes, you do not need to modify the previous code.

This is in line with the closure principle.

Let's take a look at the Code:

MyInterface, MyClassOne, and MyClassTwo remain unchanged.

Add the following interfaces and classes:

 

Package com. mode. create;


Public interface Provider {

Public MyInterface produce ();

}

 

 

Package com. mode. create;


Public class MyFactoryOne implements Provider {


@ Override

Public MyInterface produce (){

Return new MyClassOne ();

}


}

 

 

Package com. mode. create;


Public class MyFactoryTwo implements Provider {


@ Override

Public MyInterface produce (){

Return new MyClassTwo ();

}


}

Modify the test FactoryTest class as follows:

 

Package com. mode. create;


Public class FactoryTest {


Public static void main (String [] args ){

Provider provider = new MyFactoryOne ();

MyInterface myi = provider. produce ();

Myi. print ();

}


}

The running result is still clear.

Review: The Abstract Factory mode is to create multiple factory classes. Once new functions need to be added, new factory classes can be directly added without modifying the previous code.

3.3 Singleton Mode

The Singleton mode does not require much explanation.

Check the Code directly:

 

Package test;


Public class MyObject {


Private static MyObject myObject;


Private MyObject (){

}


Public static MyObject getInstance (){

If (myObject! = Null ){

} Else {

MyObject = new MyObject ();

}

Return myObject;

}


}

However, this will cause multithreading. For more information, see Chapter 6 in Java multi-threaded programming core technology.

3.4 builder Mode

Builder mode: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.

Literally, it is very abstract. In fact, it is also very abstract !!!!

The builder mode usually includes the following roles:

(1) Builder: provides an abstract interface to standardize the construction of each component of a product object. This interface specifies which parts of a complex object should be created, and does not involve the creation of specific object parts.

(2) ConcreteBuilder: implements the Builder interface to create different parts of complex objects based on different business logic. After the construction process is complete, provide the product instance.

(3) Director: Call a specific builder to create all parts of a complex object. The instructor does not involve the information of a specific product. He is only responsible for ensuring that all parts of the object are completely created or created in a certain order.

(4) Product: the complex object to be created.

Building a villain in game development often requires that the villain must include the head, body, and foot.

Let's take a look at the following code:

Product (the complex object to be created .) :

 

Package com. mode. create;


Public class Person {


Private String head;

Private String body;

Private String foot;


Public String getHead (){

Return head;

}


Public void setHead (String head ){

This. head = head;

}


Public String getBody (){

Return body;

}


Public void setBody (String body ){

This. body = body;

}


Public String getFoot (){

Return foot;

}


Public void setFoot (String foot ){

This. foot = foot;

}

}

Builder (provides an abstract interface to standardize the construction of each component of a product object. This interface specifies which parts of a complex object should be created, and does not involve the creation of specific object parts .) :

 

Package com. mode. create;


Public interface PersonBuilder {

Void buildHead ();

Void buildBody ();

Void buildFoot ();

Person buildPerson ();

}

ConcreteBuilder (implements the Builder interface to create different parts of complex objects based on different business logic. Provide product instances after the construction process is complete .) :

 

Package com. mode. create;


Public class ManBuilder implements PersonBuilder {


Person person;


Public ManBuilder (){

Person = new Person ();

}


Public void buildBody (){

Person. setBody ("Building a man's body ");

}


Public void buildFoot (){

Person. setFoot ("building man's feet ");

}


Public void buildHead (){

Person. setHead ("build a man's head ");

}


Public Person buildPerson (){

Return person;

}


}

Director .) :

 

Package com. mode. create;


Public class PersonDirector {

Public Person constructPerson (PersonBuilder pb ){

Pb. buildHead ();

Pb. buildBody ();

Pb. buildFoot ();

Return pb. buildPerson ();

}

}

Test class:

 

Package com. mode. create;


Public class Test {

Public static void main (String [] args ){

PersonDirector pd = new PersonDirector ();

Person person = pd. constructPerson (new ManBuilder ());

System. out. println (person. getBody ());

System. out. println (person. getFoot ());

System. out. println (person. getHead ());

}

}

Running result:

Review: builder mode: separates the construction of a complex object from its representation, so that different representations can be created during the same build process.

3.5 Prototype

The idea of this mode is to copy and clone an object as a prototype to generate a new object similar to the original object.

When talking about copying objects, I will take a look at the concept of object deep replication and deep replication in combination:

Shallow copy:After an object is copied, the variables of the basic data type are re-created, and the reference type points to the original object.

Deep replication:After copying an object, both the basic data type and the reference type are re-created. In short, deep replication is completely complete, but not complete.

Write an example of two-step replication:

 

Package com. mode. create;


Import java. io. ByteArrayInputStream;

Import java. io. ByteArrayOutputStream;

Import java. io. IOException;

Import java. io. ObjectInputStream;

Import java. io. ObjectOutputStream;

Import java. io. Serializable;


Public class Prototype implements Cloneable, Serializable {


Private static final long serialVersionUID = 1L;


Private int base;


Private Integer obj;


/* Light copy */

Public Object clone () throws CloneNotSupportedException {

// Because the Cloneable interface is an empty interface, you can define the method name of the implementation class at will.

// For example, cloneA or cloneB, because the focus here is the sentence "super. clone ()".

// Super. clone () calls the Object clone () method.

// In the Object class, clone () is native (local method)

Prototype proto = (Prototype) super. clone ();

Return proto;

}


/* Deep copy */

Public Object deepClone () throws IOException, ClassNotFoundException {


/* Write the binary stream of the current object */

ByteArrayOutputStream bos = new ByteArrayOutputStream ();

ObjectOutputStream oos = new ObjectOutputStream (bos );

Oos. writeObject (this );


/* Read the new binary abortion object */

ByteArrayInputStream bis = new ByteArrayInputStream (bos. toByteArray ());

ObjectInputStream ois = new ObjectInputStream (bis );

Return ois. readObject ();

}


Public int getBase (){

Return base;

}


Public void setBase (int base ){

This. base = base;

}


Public Integer getObj (){

Return obj;

}


Public void setObj (Integer obj ){

This. obj = obj;

}



}

Test class:

 

Package com. mode. create;


Import java. io. IOException;


Public class Test {

Public static void main (String [] args) throws CloneNotSupportedException,

ClassNotFoundException, IOException {

Prototype prototype = new Prototype ();

Prototype. setBase (1 );

Prototype. setObj (new Integer (2 ));

/* Light copy */

Prototype prototype1 = (Prototype) prototype. clone ();

/* Deep copy */

Prototype prototype2 = (Prototype) prototype. deepClone ();

System. out. println (prototype1.getObj () = prototype1.getObj ());

System. out. println (prototype1.getObj () = prototype2.getObj ());

}

}

Running result:

Head of Java

No.: javatuanzhang

Sharing Java technical expertise on a daily basis

Long-pressed QR code recognition

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.