设计模式(2018.9.28)

一、单例模式

    1. 懒汉模式:
      1.1 双重校验锁:利用synchronized关键字防止线程冲突。
      1.2 枚举类:利用枚举类来进行统一的初始化。
      1.3 线程安全的懒汉模式:内部类的单例模式(java并发编程推荐的单例模式创建方式:内部类Holder)。
public class Configurator {
  
    private Configurator(){
        
    }

    //java并发编程推荐的单例模式创建方式:静态内部类Holder
    public Configurator getInstance(){
        return Holder.INSTANCE;
    }
    
    private static class Holder{
        private static final Configurator INSTANCE = new Configurator();
    }

}

4.懒汉模式及双重判断加同步方式:「TextToSpeechUtil」(https://www.jianshu.com/p/ba74a92afbbe)

public class TextToSpeechUtil {

    //如果面对高并发的情况,可采用懒汉模式及双重判断加同步的方式:线程安全;延迟加载;效率较高
    private static TextToSpeechUtil instance = null;
    //构造方法
    private TextToSpeechUtil(Context context){
        initTextToSpeech(context);

    }
    public static TextToSpeechUtil getInstance(Context context){
        if(instance == null){
            synchronized(TextToSpeechUtil.class){
                if(instance==null){
                    instance = new TextToSpeechUtil(context);
                }
            }
        }
        return instance;
    }

}

二、建造者模式

    1. 标准版建造者模式
    1. Android简化版建造者模式
      (1)AlertDialog源码
      (2)RestCreator
package comi.example.liy.latte.net;

import java.util.concurrent.TimeUnit;

import comi.example.liy.latte.app.ConfigeType;
import comi.example.liy.latte.app.Latte;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by liy on 2018-10-19 15:25
 * java并发编程推荐的单例模式创建方式:内部类Holder
 * 简化的建造者模式
 */
public class RestCreator {

    private  static final class RetrofitHolder{
        private static final String BASE_URL = (String) Latte.getConfigurations().get(ConfigeType.API_HOST);
        //简化的建造者模式
        private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
    }

    private static final class OKHttpHolder{
        private static final int TIME_OUT = 60;
        private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT,TimeUnit.SECONDS)
                .build();
    }

    //java并发编程推荐的单例模式创建方式:内部类Holder
    public static RestService getRestService(){
        return RestServiceHolder.REST_SERVICE;
    }

    private static final class RestServiceHolder{
        private static final RestService REST_SERVICE =
                RetrofitHolder.RETROFIT_CLIENT.create(RestService.class);
    }

}

你可能感兴趣的:(设计模式(2018.9.28))