Android Single example mode Singleton simple instance design pattern parsing _java

Source: Internet
Author: User
Tags static class

Analysis of simple example design pattern Singleton single case pattern

Objective

Today I'm going to make a comprehensive summary of the most common design patterns in Android development-the single example pattern.

About the design pattern of the introduction, you can see what I wrote before: 1 minutes to fully understand the "design mode"

Directory

1. Introducing

1.1 What is the problem of solving

As I said before, the design pattern is a solution to a particular kind of problem, so what is the solution to the problem of a single case pattern ?

Meaning: single example = an instance;

Problem solved: Reducing the coupling between objects

Workaround: Singleton mode, which implements a class with only one instantiated object and provides a global access point

1.2 Examples introduced

Next I use an example to introduce the singleton pattern

Background: There is a plastic production plant, but there is only one warehouse.

Purpose: To use code to implement warehouse management

Existing practices: Building warehouse and worker classes

Among them, the number of quantity= goods in the warehouse class, and the handling methods in the Worker class Movein (int i) and moveout (int i).

The problem: Through the test found that each worker to carry the operation will be a new warehouse, that is, the goods are not placed in the same warehouse, this is how it? (Look at the code below)

Package Scut.designmodel.SingletonPattern;

  Warehouse class Storehouse {private int quantity = 100;
  public void setquantity (int quantity) {this.quantity = quantity;
  public int getquantity () {return quantity;
  }//Freight forwarder Human class carrier{public storehouse mstorehouse;
  Public Carrier (Storehouse storehouse) {mstorehouse = storehouse;
  //move into warehouse public void Movein (int i) {mstorehouse.setquantity (mstorehouse.getquantity () +i);
  //Move out of warehouse public void moveout (int i) {mstorehouse.setquantity (mstorehouse.getquantity ()-i); }//Worker handling test public class Singlepattern {public static void main (string[] args) {Storehouse mStoreHouse1 = new Sto
    Rehouse ();
    Storehouse MStoreHouse2 = new Storehouse ();
    Carrier Carrier1 = new Carrier (MSTOREHOUSE1);

    Carrier Carrier2 = new Carrier (MSTOREHOUSE2); System.out.println ("Two is the same one?")

    "); if (Mstorehouse1.equals (MSTOREHOUSE2)) {//is used equals instead of = = Symbol, because the = = Symbol only compares the address of two objects System.out.println ("is the sameOne ");
    }else {System.out.println ("not the same");
    After the porter has finished carrying the goods, report the quantity of the warehouse goods Carrier1.movein (30);
    SYSTEM.OUT.PRINTLN ("Warehouse commodity allowance:" +carrier1.mstorehouse.getquantity ());
    Carrier2.moveout (50);
  SYSTEM.OUT.PRINTLN ("Warehouse commodity allowance:" +carrier2.mstorehouse.getquantity ()); }
}

Results:

Two is the same one?
not the same
warehouse. Commodity allowance: 130
Warehouse merchandise allowance: 50

2. Single Case Model Introduction

2.1 Problems solved (application scenario)

Conflict: From the results above, it can be seen that worker class operations are obviously not the same warehouse instance.

Objective: All workers operate in the same warehouse instance

A singleton pattern is a solution to this type of problem: Implementing a class with only one instantiated object and providing a global access point 2.2 working principle

In Java, we manipulate these classes by using objects (after class instantiation), class instantiation is done by its construction method , and if you want to implement a class with only one instantiated object, work on the method of constructing the class:

General implementation of a single case pattern: (with steps to use)

public class Singleton {
//1. Create a private variable ourinstance (a unique instance that records Singleton)
//2. Internal instantiation
  private static Singleton ourinstance = new Singleton ();

3. Privatize the class's construction method and do not let the external invocation constructor instantiate
  private Singleton () {
  }
//4. Defines a public method that provides a globally unique access point for the class
//5. External by calling the GetInstance () method to return a unique instance public
  static Singleton newinstance () {returns
    ourinstance;
  }
}

Well, the introduction and principle of the single case model should be understood? So now we're going to solve the problem of "warehouse is not a" that appears on the top of the small.

2.3 Example Introduction

Small to use a single example pattern to improve the code for the above example:

Package Scut.designmodel.SingletonPattern;
Import Java.util.concurrent.locks.Lock;

Import Java.util.concurrent.locks.ReentrantLock;
  Single example warehouse class Storehouse {//Warehouse commodity quantity private int quantity = 100;
  Internally instantiate private static storehouse ourinstance = new storehouse ();;
  Let the external call the GetInstance () method to return a unique instance.
  public static storehouse getinstance () {return ourinstance;
  }//enclosing constructor private storehouse () {} public void setquantity (int quantity) {this.quantity = quantity;
  public int getquantity () {return quantity;
  }//Freight forwarder Human class carrier{public storehouse mstorehouse;
  Public Carrier (Storehouse storehouse) {mstorehouse = storehouse;
  //move into warehouse public void Movein (int i) {mstorehouse.setquantity (mstorehouse.getquantity () +i);
  //Move out of warehouse public void moveout (int i) {mstorehouse.setquantity (mstorehouse.getquantity ()-i); }//Worker handling test public class Singlepattern {public static void main (string[] args) {storehouse MstoreHouse1 = Storehouse.getinstance ();
    Storehouse MStoreHouse2 = Storehouse.getinstance ();
    Carrier Carrier1 = new Carrier (MSTOREHOUSE1);

    Carrier Carrier2 = new Carrier (MSTOREHOUSE2); System.out.println ("Two is the same one?")

    ");
    if (Mstorehouse1.equals (MStoreHouse2)) {System.out.println ("is the same");
    }else {System.out.println ("not the same");
    After the porter has finished carrying the goods, report the quantity of the warehouse goods Carrier1.movein (30);
    SYSTEM.OUT.PRINTLN ("Warehouse commodity allowance:" +carrier1.mstorehouse.getquantity ());
    Carrier2.moveout (50);
  SYSTEM.OUT.PRINTLN ("Warehouse commodity allowance:" +carrier2.mstorehouse.getquantity ()); }
}

Results:

Two is the same one?
It's the same
warehouse. Commodity allowance: 130
Warehouse merchandise allowance: 80

From the result analysis, using the singleton mode, the warehouse class has only one instance of the warehouse, no longer need to worry about the stevedores into the wrong warehouse!!!

2.4 Advantages

    1. Provides controlled access to a unique instance;
    2. Because there is only one object in the system memory, the system resources can be saved, and for some objects which need to be created and destroyed frequently, the performance of the system can be improved.
    3. Can be based on the actual situation needs, in a single case model on the basis of the expansion of the two-case model, a number of cases;

2.5 Disadvantages

    1. The single class is overloaded, and the code inside may be too complex to violate the "single responsibility principle" to some extent.
    2. If the instantiated object is not exploited for a long time, it will be reclaimed by the system as garbage, which will result in the loss of the object state.

3. How to implement a single case pattern

3.1 General Conditions

A Hungry man (simplest single instance implementation)

Class Singleton {
  private static Singleton ourinstance = new Singleton ();

  Private Singleton () {
  } public

  static Singleton newinstance () {return
    ourinstance;
  }
}

Application Scenario:

    • Required to load and initialize directly at application startup
    • Single Case object requires very fast initialization and very small memory footprint

Lazy type

The biggest difference between loafers and a hungry man is the timing of the initialization of a single instance :

    • A hungry man: automatic initialization of a single case
    • Lazy: Manually invoke newinstance () when necessary to perform a single instance of initialization
Class Singleton {
  private static Singleton ourinstance = null;

  private Singleton () {
  } public

  static Sing Leton newinstance () {
  if (ourinstance = null) {
    ourinstance = new Singleton ();
    }
    Return ourinstance
  }
}

Application Scenario:

    • Single-instance initialization takes longer to operate and requires a startup speed
    • Single case has a larger memory footprint
    • A single example is used only in the case of a particular scenario, that is, to delay loading a single instance on demand.

Single case mode implementation under 3.2 multi-thread

In the case of multithreading:

    • For a hungry man single case mode: applicable, because the JVM only loads a single instance class;
    • For "Lazy single case Mode": Not applicable because "lazy" is a thread unsafe when creating a single case, and multiple threads may call the Newinstance method concurrently to create the problem of repeatedly creating a single instance object.

Solution 1: Sync lock

The use of synchronous lock synchronized (SINGLETON.CLASS) prevents multiple threads from entering simultaneously causing instance to be instantiated multiple times.

Class Singleton {
  private static Singleton ourinstance = null;

  private Singleton () {
  } public

  static Sing Leton newinstance () {
   synchronized (singleton.class) {
     if (ourinstance = null) {
      ourinstance = new Singleton ();
    }
   }
    Return ourinstance
  }
}

Solution 2: Double check lock

A layer of if is added on the basis of a synchronous lock (synchronized (Singleton.class), in order to get the object lock next time after instance has been instantiated, without having to perform synchronized (Singleton.class). thereby improving performance.

Class Singleton {
  private static Singleton ourinstance = null;

  private Singleton () {
  } public

  static Singleton newinstance () {
if (ourinstance = null) {
 synchronized (singleton.class) {
   if (ourinstance = = NULL) {
     ourinstance = new Singleton ();
    }}} Return ourinstance
  }
}

Solution 3: Static internal classes

When the JVM does class loading, the data is guaranteed to be synchronized, and we use an inner class implementation: Create an object instance inside the inner class.
As long as the internal class JVM is not used in the application, the single instance class is not loaded and the single Instance object is not created, thus enabling lazy loading and thread safety.

Class Singleton {

  ///when loading the inner class to create a single Instance object
  private static class singleton2{
   private static Singleton Ourinstance = new Singleton ();
  }
  Private Singleton () {
  } public

  static Singleton newinstance () {
    Return singleton2.ourinstance
  }
}

Solution 4: Enum type

The simplest and easiest way to implement a single example (recommended by effective Java)

The public enum singleton{

  //defines an enumerated element, which is an instance of the Singleton
  instance;

  public void DoSomething () {
  }  

}

The use of the following methods:

Singleton Singleton = singleton.instance;
Singleton.dosomething ();

5. Summary

This article mainly gives a comprehensive introduction to the single example mode, including the principle and implementation, and then I will continue to explain the other design patterns, interested to continue to pay attention to

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.