5 Types of Java Classic creation mode detailed _java

Source: Internet
Author: User
Tags abstract closure shallow copy

I. Overview

Overall, the design pattern is divided into three main categories:

(1) The creation pattern , altogether five kinds: The factory method pattern, the abstract factory pattern, the single example pattern, the builder pattern, the prototype pattern.

(2) structure mode , a total of seven kinds: Adapter mode, adorner mode, agent mode, appearance mode, bridging mode, combination mode, enjoy meta mode.

(3) behavioral pattern , a total of 11 kinds: Strategy mode, template method mode, observer mode, iterative sub-mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, intermediary mode, interpreter mode.

The six principles of design pattern

1, opening and closing principle (Open close principle)

The opening and closing principle is said to be open to expansion, to modify the closure. When the program needs to expand, can not modify the original code, to achieve a hot-swappable effect.

2, the Richter substitution principle (Liskov substitution principle)

Its official description is more abstract, can own Baidu. You can actually understand this: (1) The ability of a subclass must be greater than or equal to the parent class, that is, the method that the parent class can use, and subclasses can use it. (2) The return value is the same reason. Assuming that a parent class method returns a list, the subclass returns a ArrayList, which of course can be. If the parent class method returns a ArrayList, the subclass returns a list and it doesn't make sense. The ability of a subclass to return a value is smaller than the parent class. (3) There is also the case of throwing exceptions. Any subclass method can declare a subclass that throws a parent class method declaration exception.
You cannot declare an exception that throws a parent class without a declaration.

3. The principle of reliance reversal (dependence inversion principle)

This is the basis of the open and closed principle, the specific content: interface programming, rely on the abstract and not rely 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 in the coupling between the class meaning, from here we see, in fact, design pattern is a software design idea, from large software architecture, in order to upgrade and maintenance convenience. So there are several times in the above: reduce dependence and reduce coupling.

5. Dimitri (minimum known principle) (Demeter principle)

Why is called the least known principle, that is to say: an entity should be as little as possible with other entities interaction, making the system functional modules relatively independent.

6. Synthetic reuse principle (composite reuse principle)

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

Third, the creation of the model

The creation pattern, altogether five kinds: The factory method pattern, the abstract factory pattern, the single case pattern, the builder pattern, the prototype pattern.

3.1. Factory method mode

The factory method pattern is divided into three kinds: Common Factory mode, multiple factory method mode and static factory method mode.

3.1.1, General factory model

The common factory model is to create a factory class that creates instances of 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 my Classone (); 
    } else if ("two". Equals (Type)) {return 
      new Myclasstwo (); 
    } else { 
      System.out.println ("No type to find"); 
      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 ();
  }
 

Factorytest's running results I think it should be obvious.

To understand this: the Common factory model is to create a factory class that implements instances of classes that implement the same interface.

3.1.2, multiple factory method patterns

Multiple factory approach patterns are an improvement of the common factory approach pattern, where multiple factory method models provide multiple factory methods to create objects separately.

Looking directly at the code, we 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 results of the operation are also very obvious.

Again to understand this sentence: Multiple factory method Patterns, is the common factory method model improvement, multiple factory method mode is to provide a number of factory methods, respectively, create objects.

3.1.3, static Factory method mode

Static Factory method mode, which is set to static in the above multiple factory method modes, without the need to create an instance and call directly.

Looking directly at the code, we 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 results of the operation are still obvious.

Review: Static factory method mode, the above multiple factory method mode to static, do not need to create an instance, call directly.

3.2. Abstract Factory model

The problem with the factory method pattern is that the creation of the class relies on the factory class, which means that if you want to expand the program, you must modify the factory class, which violates the closure principle.

To solve this problem, let's look at the abstract factory pattern: Create multiple factory classes so that once you need to add new functionality, add new factory classes directly, without needing to modify the previous code.

This is consistent with the closure principle.

Let's look at the code here:

MyInterface, Myclassone, myclasstwo 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 class Factorytest 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 results of the operation are still apparent.

Again: Abstract Factory mode is the creation of multiple factory classes, so that once you need to add new functionality, add new factory classes directly, no need to modify the previous code.

3.3. Single case mode

Single case mode, do not need too much explanation.

Just look at the code:

Package test;
 
public class MyObject {
 
  private static MyObject MyObject;
 
  Private MyObject () {
  } public
 
  static MyObject getinstance () {
    if (MyObject!= null) {
    } else {
      Myobjec t = new MyObject ();
    }
    Return MyObject
  }
 
}

However, this will cause multithreading problems, the detailed explanation can see "Java Multithreaded Programming core technology," the sixth chapter of the book.

3.4. Builder model

Builder pattern: The separation of a complex object's construction from its representation, allowing the same build process to create different representations.

It's literally very abstract, and it's actually very abstract!!!!

The builder pattern typically includes the following roles:

(1) Builder: An abstract interface is given to standardize the construction of each component of a Product object. This interface specifies which parts of a complex object to create, and does not involve the creation of specific object parts.

(2) ConcreteBuilder: Implementation of the Builder interface, for different business logic, to materialize the creation of various parts of complex objects. Provide an example of the product after the construction process is completed.

(3) Director: Call specific builders to create parts of complex objects that do not involve specific product information in the mentor, but are responsible for ensuring that the objects are created or created in a certain order.

(4) Product: The complex object to create.

The construction of the villain in game development is often the case, the requirement is: The villain must include the head, body and feet.

Let's look at the following code:

Product (the complex object to create. ):

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 (gives an abstract interface to standardize the construction of each component of a product object.) This interface specifies which parts of a complex object to create, 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, which embodies the creation of various parts of complex objects for different business logic. Provide an example of the product after the construction process is completed. ):

Package com.mode.create;
 
public class Manbuilder implements Personbuilder {Person of person
 
  ;
 
  Public Manbuilder () {Person
    = new person ();
  }
 
  public void Buildbody () {
    person.setbody ("Build a man's body");
  }
 
  public void Buildfoot () {
    person.setfoot ("Build man's Foot");
  }
 
  public void Buildhead () {
    person.sethead ("Build Man's Head");
  }
 
  Public Person Buildperson () {return person
    ;
  }
 
}

Director (calls specific builders to create parts of complex objects that do not involve specific product information in the mentor, only to ensure that each part of the object is completely created or created in a certain order). ):

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 ());
  }

Run Result:

Review: Builder pattern: Separates the construction of a complex object from its representation, allowing the same build process to create different representations.

3.5. Prototype mode

The idea of this pattern is to copy and clone an object as a prototype, producing a new object similar to the original object.

Speaking of copying objects, I will combine the object's shallow copy and deep copy to say, first of all need to understand object deep, shallow copy concept:

Shallow copy: When an object is copied, a variable of the base data type is recreated, and the reference type is pointed to or pointed to by the original object.

Deep copy: After copying an object, both the base data type and the reference type are recreated. In short, the deep copy is completely copied, and the shallow copy is not thorough.

Write an example of a shade copy:

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; /* Shallow copy/Public Object clone () throws Clonenotsupportedexception {//Because the Cloneable interface is an empty interface, you can define the method name of the implementation class//AS CL
    Onea or CLONEB, because the emphasis here is that the super.clone ()//Super.clone () calls the object's clone () method, and in the object class, the Clone () is the native (local method)
    Prototype proto = (Prototype) super.clone ();
  return proto; }/* Deep copy/public object Deepclone () throws IOException, ClassNotFoundException {/* Writes the current object's binary stream * * * Bytea
    Rrayoutputstream BOS = new Bytearrayoutputstream ();
    ObjectOutputStream oos = new ObjectOutputStream (BOS);
 
    Oos.writeobject (this); /* Read the new object generated by the binary stream/* 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));
    /* Shallow 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 ());
  }

Run Result:

The above is the entire content of this article, I hope to help you learn.

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.