Before blowing sequence

As a programmer, want to see the gap with others, in addition to the necessary blowing skills, bucket chart skills, that is still the most important point – code ability! So how can you successfully install the force through your own code in many jokes and old drivers? As a programmer, you must understand, learn, and use the killer card to design patterns

What are design patterns

You can think of it this way:

  • Generally speaking, there is no unified definition of the design pattern of the program. It is a kind of scheme that can be copied and reused by the developers continuously accumulated in the development process
  • Design patterns are reproducible solutions to design problems commonly encountered by programmers
  • Design patterns establish a set of rules that describe how to accomplish specific tasks in the software development domain
  • Design patterns focus on reusing repeatable structural designs
  • Design pattern recognition and determination of abstract relationships at the class and instance levels or component levels

    Summary: Design patterns are a popular way of thinking about design problems among designers. They are a set of repeatedly used, widely known, catalogued code design experiences.

    The advantage of using design patterns is to make the code reusable, make it easier to understand and ensure the reliability of the code.

At the same time, there are some differences in design patterns in different languages. Here, we will summarize and learn several design patterns related to Android (After all, the design pattern of Agog cannot be surpassed).

The singleton pattern

Usage scenarios

In the application, there should be only one ImageLoader global object. In the ImageLoader, there are network caches, thread pools, request queues, etc., which are very resource consuming. Therefore, we cannot let it construct multiple instancesCopy the code

define

Ensure that there is only one instance of a class that needs to be instantiated and made available to the systemCopy the code

constitute

  • Private constructor
  • Private static variables (same as instances of the class)
  • A common static method returns an instance

Type of implementation

  • The hungry mode
  • Static inner class
  • Lazy loading
The hungry type
This instance is initialized when the class is loaded. Creating a singleton instance is simple and easy, but there is a downside: the instance may not be usedCopy the code
public class Singleton {

    private static Singleton singleton = new Singleton();

    private Singleton(){
    }

    public static Singleton getSingleton() {returnsingleton; }}Copy the code
This creates a singleton pattern that, in addition to the drawbacks mentioned above, does not have any exception handlingCopy the code
Static inner class
public class Singleton {

    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    }

    private Singleton(){
    }

    public static Singleton getSingleton() {returnSingletonHolder.singleton; }}Copy the code
Static inner classes are not initialized when they are first loaded, and are created only when getSingleton() is used. Therefore, this approach not only ensures thread safety, but also ensures singleton uniqueness, while delaying singleton instantiation, so it is recommended to use this approach.Copy the code
Lazy loading
Create an instance of this class when we need to use it.Copy the code
public class Singleton {

    private static Singleton singleton = null;

    private Singleton(){
    }

    public static Singleton getSingleton() {if(singleton == null){
            singleton = new Singleton();
        }
        returnsingleton; }}Copy the code
Creating instances in this way is fine in a single thread, but creating multiple instances in multiple threads is unsafe, so we need to work on that.Copy the code
public class Singleton {

    private static Singleton singleton = null;

    private Singleton(){
    }

    public static synchronized Singleton getSingleton() {if(singleton == null){
            singleton = new Singleton();
        }
        returnsingleton; }}Copy the code

Above we have been optimized to solve the problem of creating multiple instances of multiple threads, and provide thread safety. So did you think you were done? Don’t be too young: synchronized modifiers the getSingleton() method, so this can affect performance! This pattern is generally not recommended because we synchronize every time we call the getSingleton() method, causing unnecessary resource consumption, which is the biggest problem with slackness.

We also need to optimize the above code:

public class Singleton {

    private static Singleton singleton = null;

    private Singleton(){
    }

    public static Singleton getSingleton() {if(singleton == null){
            synchronized(Singleton.class){
                if(singleton == null){
                    singleton = newSingleton(); }}}returnsingleton; }}Copy the code

Once again, by optimizing our code, we can see that the getSingleton method nulls twice. The first is for unnecessary synchronization, and the second is for creating an instance if it is empty.

At this point, we can not only initialize the singleton when needed, but also keep it thread-safe and ensure that the call to getSingleton after the singleton is initialized will not lock the synchronization

conclusion

The singleton pattern is a frequently used design pattern. Lazy loading pattern and static internal class pattern are recommended for efficiencyCopy the code

Advantages:

  1. The singleton pattern has only one instance in memory, and the memory cost is small.
  2. Avoid multiple processing of resources
  3. You can set up global access classes to handle and optimize shared resources

Disadvantages:

  1. Without interfaces, expansion is difficult
  2. If you hold a context object, it will leak memory.