builder mode 1 of Glide design pattern [GlideBuilder]

Glide's multiple combination usage records - not all of them are tested in person, so you can choose according to your actual needs
builder mode 1 of Glide design pattern [GlideBuilder]
Glide design pattern builder mode 2 [RequestBuilder]
builder mode 3 of Glide design pattern [RequestOptions] [BaseRequestOptions]
builder mode 4 Summary of Glide design pattern [memorysize calculator] [GlideExecutor] [PreFillType] [LazyHeaders]

Official definition

The intent of the Builder design pattern is to separate the
construction of a complex object from its representation. By doing so
the same construction process can create different representations.
Separate the construction of a complex object from its representation, so that the same construction process can create different representations

Scene description

Class has many construction parameters. It is recommended to have more than 4, and most of these parameters are optional. The builder model can be considered

Glide.with(myFragment).load(url).centerCrop().placeholder(R.drawable.loading_spinner) .into(myImageView);

This usage seems to have more parameters. When creating the singleton mode
Mainly watching com bumptech. Glide. Glidebuilder is the builder of the object that creates Glide. The build method is as follows:

com.bumptech.glide.GlideBuilder

 @NonNull
  Glide build(@NonNull Context context) {
    if (sourceExecutor == null) {
      sourceExecutor = GlideExecutor.newSourceExecutor();
    }

    if (diskCacheExecutor == null) {
      diskCacheExecutor = GlideExecutor.newDiskCacheExecutor();
    }

    if (animationExecutor == null) {
      animationExecutor = GlideExecutor.newAnimationExecutor();
    }

    if (memorySizeCalculator == null) {
      memorySizeCalculator = new MemorySizeCalculator.Builder(context).build();
    }

    if (connectivityMonitorFactory == null) {
      connectivityMonitorFactory = new DefaultConnectivityMonitorFactory();
    }

    if (bitmapPool == null) {
      int size = memorySizeCalculator.getBitmapPoolSize();
      if (size > 0) {
        bitmapPool = new LruBitmapPool(size);
      } else {
        bitmapPool = new BitmapPoolAdapter();
      }
    }

    if (arrayPool == null) {
      arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes());
    }

    if (memoryCache == null) {
      memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize());
    }

    if (diskCacheFactory == null) {
      diskCacheFactory = new InternalCacheDiskCacheFactory(context);
    }

    if (engine == null) {
      engine =
          new Engine(
              memoryCache,
              diskCacheFactory,
              diskCacheExecutor,
              sourceExecutor,
              GlideExecutor.newUnlimitedSourceExecutor(),
              animationExecutor,
              isActiveResourceRetentionAllowed);
    }

    if (defaultRequestListeners == null) {
      defaultRequestListeners = Collections.emptyList();
    } else {
      defaultRequestListeners = Collections.unmodifiableList(defaultRequestListeners);
    }

    GlideExperiments experiments = glideExperimentsBuilder.build();
    RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory, experiments);

    return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptionsFactory,
        defaultTransitionOptions,
        defaultRequestListeners,
        experiments);
  }

After visual inspection, there are 12 default parameters, and most of them are optional and customizable.

com. bumptech. glide. Parameter list for glidebuilder

private final Map<Class<?>, TransitionOptions<?, ?>> defaultTransitionOptions = new ArrayMap<>();
  private final GlideExperiments.Builder glideExperimentsBuilder = new GlideExperiments.Builder();
  private Engine engine;
  private BitmapPool bitmapPool;
  private ArrayPool arrayPool;
  private MemoryCache memoryCache;
  private GlideExecutor sourceExecutor;
  private GlideExecutor diskCacheExecutor;
  private DiskCache.Factory diskCacheFactory;
  private MemorySizeCalculator memorySizeCalculator;
  private ConnectivityMonitorFactory connectivityMonitorFactory;
  private int logLevel = Log.INFO;
  private RequestOptionsFactory defaultRequestOptionsFactory =
      new RequestOptionsFactory(). . . ;
  @Nullable private RequestManagerFactory requestManagerFactory;
  private GlideExecutor animationExecutor;
  private boolean isActiveResourceRetentionAllowed;
  @Nullable private List<RequestListener<Object>> defaultRequestListeners;

Configurable properties are:

 /**
   * Sets the {@link com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool} implementation to use
   * to store and retrieve reused {@link android.graphics.Bitmap}s.
   *
   * @param bitmapPool The pool to use.
   * @return This builder.
   */
	set up BitmapPool(Refer to Appendix 1) for use
	Storage and retrieval reuse Bitmaps. 
  @NonNull
  public GlideBuilder setBitmapPool(@Nullable BitmapPool bitmapPool) {
. . . 
  /**
   * Sets the {@link ArrayPool} implementation to allow variable sized arrays to be stored and
   * retrieved as needed.
   *
   * @param arrayPool The pool to use.
   * @return This builder.
   */
  @NonNull
   Retrieve and reuse as needed
   set up{@link ArrayPool((see Appendix 1)}Implementation to allow storage of variable size arrays and
  public GlideBuilder setArrayPool(@Nullable ArrayPool arrayPool) {
. . . 
/**
   * Sets the {@link com.bumptech.glide.load.engine.cache.MemoryCache} implementation to store
   * {@link com.bumptech.glide.load.engine.Resource}s that are not currently in use.
   *
   * @param memoryCache The cache to use.
   * @return This builder.
   */
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
 set up com.bumptech.glide.load.engine.cache.MemoryCache(Refer to Appendix 1) for storage com.bumptech.glide.load.engine.Resource(Refer to Appendix 1) or not currently used Resource
  public GlideBuilder setMemoryCache(@Nullable MemoryCache memoryCache) {
. . . 
/**
   * Sets the {@link com.bumptech.glide.load.engine.cache.DiskCache.Factory} implementation to use
   * to construct the {@link com.bumptech.glide.load.engine.cache.DiskCache} to use to store {@link
   * com.bumptech.glide.load.engine.Resource} data on disk.
   *
   * @param diskCacheFactory The disk cache factory to use.
   * @return This builder.
   */
   set up DiskCache.Factory(Refer to Appendix 1) interface implementation for use DiskCache(Refer to the construction object in Appendix 1). Used to store resource data to disk
   Parameters: diskCacheFactory The disk cache factory to be used (so the next article is factory mode, hee hee)
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
  public GlideBuilder setDiskCache(@Nullable DiskCache.Factory diskCacheFactory) {
. . . 
 /**
   * Sets the {@link GlideExecutor} to use when retrieving {@link
   * com.bumptech.glide.load.engine.Resource}s that are not already in the cache.
   *
   * <p>The thread count defaults to the number of cores available on the device, with a maximum of
   * 4.
   *
   * <p>Use the {@link GlideExecutor#newSourceExecutor()} methods if you'd like to specify options
   * for the source executor.
   *
   * @param service The ExecutorService to use.
   * @return This builder.
   * @see #setDiskCacheExecutor(GlideExecutor)
   * @see GlideExecutor
   * @deprecated Use {@link #setSourceExecutor(GlideExecutor)}
   */
   set up GlideExecutor(Refer to Appendix 1) for retrieving resources that are not in the cache.
   The number of threads defaults to the number of cores available on the device, with a maximum of 4
   Default use GlideExecutor#The newSourceExecutor() method can also specify thread pool execution
   parameter service To use ExecutorService. 
   **This method is deprecated**
   @Deprecated
  public GlideBuilder setResizeExecutor(@Nullable GlideExecutor service) {
  	return setSourceExecutor(service);
  }
. . . 
 /**
   * Sets the {@link GlideExecutor} to use when retrieving {@link
   * com.bumptech.glide.load.engine.Resource}s that are not already in the cache.
   *
   * <p>The thread count defaults to the number of cores available on the device, with a maximum of
   * 4.
   *
   * <p>Use the {@link GlideExecutor#newSourceExecutor()} methods if you'd like to specify options
   * for the source executor.
   *
   * @param service The ExecutorService to use.
   * @return This builder.
   * @see #setDiskCacheExecutor(GlideExecutor)
   * @see GlideExecutor
   */
   with setResizeExecutor Is the same function. It is generally used for compatible versions
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
  public GlideBuilder setSourceExecutor(@Nullable GlideExecutor service) {
. . . 
 /**
   * Sets the {@link GlideExecutor} to use when retrieving {@link
   * com.bumptech.glide.load.engine.Resource}s that are currently in Glide's disk caches.
   *
   * <p>Defaults to a single thread which is usually the best combination of memory usage, jank, and
   * performance, even on high end devices.
   *
   * <p>Use the {@link GlideExecutor#newDiskCacheExecutor()} if you'd like to specify options for
   * the disk cache executor.
   *
   * @param service The {@link GlideExecutor} to use.
   * @return This builder.
   * @see #setSourceExecutor(GlideExecutor)
   * @see GlideExecutor
   */
   set up GlideExecutor(Refer to Appendix 1) to retrieve the current Glide Resources in disk cache for
   The default is a single thread, which is usually memory usage jank And, even on high-end devices.
   Default use GlideExecutor#newDiskCacheExecutor() (refer to Appendix 1) to specify the disk cache executor.
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
  public GlideBuilder setDiskCacheExecutor(@Nullable GlideExecutor service) {
. . . 
  /**
   * Sets the {@link GlideExecutor} to use when loading frames of animated images and particularly
   * of {@link com.bumptech.glide.load.resource.gif.GifDrawable}s.
   *
   * <p>Defaults to one or two threads, depending on the number of cores available.
   *
   * <p>Use the {@link GlideExecutor#newAnimationExecutor()} methods if you'd like to specify
   * options for the animation executor.
   *
   * @param service The {@link GlideExecutor} to use.
   * @return This builder.
   */
   set up GlideExecutor(Refer to Appendix 1) for loading animation image frames, especially GifDrawables
   The default is one or two threads, depending on the number of cores available.
   Default use GlideExecutor#Newanimationexecution() (refer to Appendix 1) method. You can customize and select the animation actuator.
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
  public GlideBuilder setAnimationExecutor(@Nullable GlideExecutor service) {
  . . . 
   /**
   * Sets the default {@link RequestOptions} to use for all loads across the app.
   *
   * <p>Applying additional options with {@link RequestBuilder#apply(BaseRequestOptions)} will
   * override defaults set here.
   *
   * @see #setDefaultRequestOptions(RequestOptionsFactory)
   * @param requestOptions The options to use by default.
   * @return This builder.
   */
   Set default RequestOptions(Refer to Appendix 1) for all loaded applications
   Apply additional options and RequestBuilder((see Appendix 1)#apply(BaseRequestOptions) will
   Override the default values set here.
  public GlideBuilder setDefaultRequestOptions(@Nullable final RequestOptions requestOptions) {
. . . 
/**
   * Sets a factory for the default {@link RequestOptions} to use for all loads across the app and
   * returns this {@code GlideBuilder}.
   *
   * <p>This factory will <em>NOT</em> be called once per load. Instead it will be called a handful
   * of times and memoized. It's not safe to assume that this factory will be called again for every
   * new load.
   *
   * <p>Applying additional options with {@link RequestBuilder#apply(BaseRequestOptions)} will
   * override defaults set here.
   *
   * @see #setDefaultRequestOptions(RequestOptionsFactory)
   */
   Is the default RequestOptions Set up a factory for all loads of the application and return this GlideBuilder. 
   This factory will not be called every time it is loaded. Instead, it will be called several times and remembered. For each new load, the factory is called again, which is not safe.
   Applying other options will override the default settings RequestBuilder#apply(BaseRequestOptions)
  @NonNull
  public GlideBuilder setDefaultRequestOptions(@NonNull RequestOptionsFactory factory) {
. . . 
  /**
   * Sets the default {@link TransitionOptions} to use when starting a request that will load a
   * resource with the given {@link Class}.
   *
   * <p>It's preferable but not required for the requested resource class to match the resource
   * class applied here as long as the resource class applied here is assignable from the requested
   * resource class. For example you can set a default transition for {@link
   * android.graphics.drawable.Drawable} and that default transition will be used if you
   * subsequently start requests for specific {@link android.graphics.drawable.Drawable} types like
   * {@link com.bumptech.glide.load.resource.gif.GifDrawable} or {@link
   * android.graphics.drawable.BitmapDrawable}. Specific types are always preferred so if you
   * register a default transition for both {@link android.graphics.drawable.Drawable} and {@link
   * android.graphics.drawable.BitmapDrawable} and then start a request for {@link
   * android.graphics.drawable.BitmapDrawable}s, the transition you registered for {@link
   * android.graphics.drawable.BitmapDrawable}s will be used.
   */
   set default TransitionOptions,So that a given will be used at startup Class Used when loading requests for resources.
As long as the resource class applied here can be allocated from the requested resource class, the requested resource class is best matched with the resource class applied here, but this is not necessary. For example, you can Drawable Set a default conversion if you then start requesting a specific conversion Drawable Type, e.g GifDrawable or BitmapDrawable,Then the default conversion will be used. Specific types are always preferred, so if you register a default transition, you can both draw and BitmapDrawable,Then start a BitmapDrawables Your request, you registered BitmapDrawables The transition will be used.

It's hard to explain the notes. But its role UI I like design very much: it is for effect conversion. For example: fillet, transparency, Gaussian blur, that is, the transformation of image clipping processing such as ground glass, round head, etc.
  // Public API.
  @SuppressWarnings("unused")
  @NonNull
  public <T> GlideBuilder setDefaultTransitionOptions(
. . . 
 /**
   * Sets the {@link MemorySizeCalculator} to use to calculate maximum sizes for default {@link
   * MemoryCache MemoryCaches} and/or default {@link BitmapPool BitmapPools}.
   *
   * @see #setMemorySizeCalculator(MemorySizeCalculator)
   * @param builder The builder to use (will not be modified).
   * @return This builder.
   */
   set up MemorySizeCalculator Used to calculate the default MemoryCache and/Or default BitmapPool BitmapPools The maximum size of the.
Given MemorySizeCalculator It will not affect the passage setBitmapPool(BitmapPool)or setMemoryCache(MemoryCache)Provides a custom pool or cache.
  // Public API.
  @SuppressWarnings("unused")
  @NonNull
  set up MemorySizeCalculator Used to calculate the default MemoryCache and/Or default BitmapPool BitmapPools The maximum size of the.
  public GlideBuilder setMemorySizeCalculator(@NonNull MemorySizeCalculator.Builder builder) {
 		return setMemorySizeCalculator(builder.build());
  }
  
/**
   * Sets the {@link MemorySizeCalculator} to use to calculate maximum sizes for default {@link
   * MemoryCache MemoryCaches} and/or default {@link BitmapPool BitmapPools}.
   *
   * <p>The given {@link MemorySizeCalculator} will not affect custom pools or caches provided via
   * {@link #setBitmapPool(BitmapPool)} or {@link #setMemoryCache(MemoryCache)}.
   *
   * @param calculator The calculator to use.
   * @return This builder.
   */
   set up MemorySizeCalculator Used to calculate the default MemoryCache and/Or default BitmapPool BitmapPools The maximum size of the.
Given MemorySizeCalculator Does not affect custom pools or caches provided through
setBitmapPool (BitmapPool)or setMemoryCache (MemoryCache). 
  // Public API.
  @SuppressWarnings("WeakerAccess")
  @NonNull
  public GlideBuilder setMemorySizeCalculator(@Nullable MemorySizeCalculator calculator) {
. . . 
  /**
   * Sets the {@link com.bumptech.glide.manager.ConnectivityMonitorFactory} to use to notify {@link
   * com.bumptech.glide.RequestManager} of connectivity events. If not set {@link
   * com.bumptech.glide.manager.DefaultConnectivityMonitorFactory} would be used.
   *
   * @param factory The factory to use
   * @return This builder.
   */
   set up ConnectivityMonitorFactory To inform RequestManager Connect events. If not set, the DefaultConnectivityMonitorFactory. 

ConnectivityMonitorFactory: The network connection monitor factory is another [factory mode] application
  // Public API.
  @SuppressWarnings("unused")
  @NonNull
  public GlideBuilder setConnectivityMonitorFactory(@Nullable ConnectivityMonitorFactory factory) {
. . . 
 /**
   * Sets a log level constant from those in {@link Log} to indicate the desired log verbosity.
   *
   * <p>The level must be one of {@link Log#VERBOSE}, {@link Log#DEBUG}, {@link Log#INFO}, {@link
   * Log#WARN}, or {@link Log#ERROR}.
   *
   * <p>{@link Log#VERBOSE} means one or more lines will be logged per request, including timing
   * logs and failures. {@link Log#DEBUG} means at most one line will be logged per successful
   * request, including timing logs, although many lines may be logged for failures including
   * multiple complete stack traces. {@link Log#INFO} means failed loads will be logged including
   * multiple complete stack traces, but successful loads will not be logged at all. {@link
   * Log#WARN} means only summaries of failed loads will be logged. {@link Log#ERROR} means only
   * exceptional cases will be logged.
   *
   * <p>All logs will be logged using the 'Glide' tag.
   *
   * <p>Many other debugging logs are available in individual classes. The log level supplied here
   * only controls a small set of informative and well formatted logs. Users wishing to debug
   * certain aspects of the library can look for individual <code>TAG</code> variables at the tops
   * of classes and use <code>adb shell setprop log.tag.TAG</code> to enable or disable any relevant
   * tags.
   *
   * @param logLevel The log level to use from {@link Log}.
   * @return This builder.
   */
   Set a log level constant from log to indicate the desired level of log detail.
The level must be“ VERBOSE","DEBUG","INFO","WARN"Or“ ERROR"One of them.

Log#VERBOSE This means that each request will record one or more lines, including timing logs and failures. Log#DEBUG This means that each successful request will record at most one line of log, including timing log, although many lines of failed logs may be recorded, including multiple complete stack traces. Log#INFO This means that failed loads will be recorded, including multiple complete stack traces, but successful loads will not be recorded at all. Log#WARN Indicates that only summaries of failed loads are logged. journal#ERROR means that only exceptions will be recorded. All logs will be recorded using the 'Glide' tag. Many other debug logs can be used in separate classes. The log level provided here controls only a small number of informative and well formed logs. Users who want to debug some aspects of the library can find a single < code > tag < / code > variable at the top of the class and use < code > ADB shell setprop log tag.  Tag < / code > enable or disable any related tags.
  // Public API.
  @SuppressWarnings("unused")
  @NonNull
  public GlideBuilder setLogLevel(int logLevel) {
. . . 
 /**
   * If set to {@code true}, allows Glide to re-capture resources that are loaded into {@link
   * com.bumptech.glide.request.target.Target}s which are subsequently de-referenced and garbage
   * collected without being cleared.
   *
   * <p>Defaults to {@code false}.
   *
   * <p>Glide's resource re-use system is permissive, which means that's acceptable for callers to
   * load resources into {@link com.bumptech.glide.request.target.Target}s and then never clear the
   * {@link com.bumptech.glide.request.target.Target}. To do so, Glide uses {@link
   * java.lang.ref.WeakReference}s to track resources that belong to {@link
   * com.bumptech.glide.request.target.Target}s that haven't yet been cleared. Setting this method
   * to {@code true} allows Glide to also maintain a hard reference to the underlying resource so
   * that if the {@link com.bumptech.glide.request.target.Target} is garbage collected, Glide can
   * return the underlying resource to it's memory cache so that subsequent requests will not
   * unexpectedly re-load the resource from disk or source. As a side affect, it will take the
   * system slightly longer to garbage collect the underlying resource because the weak reference
   * has to be cleared and processed before the hard reference is removed. As a result, setting this
   * method to {@code true} may transiently increase the memory usage of an application.
   *
   * <p>Leaving this method at the default {@code false} value will allow the platform to garbage
   * collect resources more quickly, but will lead to unexpected memory cache misses if callers load
   * resources into {@link com.bumptech.glide.request.target.Target}s but never clear them.
   *
   * <p>If you set this method to {@code true} you <em>must not</em> call {@link Bitmap#recycle()}
   * or mutate any Bitmaps returned by Glide. If this method is set to {@code false}, recycling or
   * mutating Bitmaps is inefficient but safe as long as you do not clear the corresponding {@link
   * com.bumptech.glide.request.target.Target} used to load the {@link Bitmap}. However, if you set
   * this method to {@code true} and recycle or mutate any returned {@link Bitmap}s or other mutable
   * resources, Glide may recover those resources and attempt to use them later on, resulting in
   * crashes, graphical corruption or undefined behavior.
   *
   * <p>Regardless of what value this method is set to, it's always good practice to clear {@link
   * com.bumptech.glide.request.target.Target}s when you're done with the corresponding resource.
   * Clearing {@link com.bumptech.glide.request.target.Target}s allows Glide to maximize resource
   * re-use, minimize memory overhead and minimize unexpected behavior resulting from edge cases. If
   * you use {@link RequestManager#clear(Target)}, calling {@link Bitmap#recycle()} or mutating
   * {@link Bitmap}s is not only unsafe, it's also totally unnecessary and should be avoided. In all
   * cases, prefer {@link RequestManager#clear(Target)} to {@link Bitmap#recycle()}.
   *
   * @return This builder.
   */
   If set to true,allow Glide Recapture the resources loaded into the target, which are then dereferenced and garbage collected without being cleaned up. The default value is false. Glide The resource reuse system is allowed, which means that the caller can load resources into Target And then never clear Target. To this end, Glide use WeakReferences To track who belongs to target Resources that have not been cleared. Set this method to true allow Glide Hard references to underlying resources are also maintained so that if Target By garbage collection, Glide The underlying resource can be returned to its in memory cache so that subsequent requests do not accidentally reload the resource from disk or source. As a side effect, the system will take longer to garbage collect the underlying resources because weak references must be cleared and processed before hard references are deleted. Therefore, set this method to true It may temporarily increase the memory usage of the application. Leave this method as the default false Value will allow the platform to garbage collect resources faster, but if the caller loads the resources into target This will result in unexpected memory cache loss. Target, but never cleared. If you set this method to true, you<em>Definitely not</em>call Bitmap#recycle() or change any Bitmap returned by Glide. If this method is set to false, recycling or mutating bitmaps is inefficient, but safe, as long as you don't clear the corresponding target for loading bitmaps. However, if you set this method to true and recycle or change any returned bitmaps or other variable resources, Glide may recover these resources and try to use them later, resulting in crashes, graphic corruption, or undefined behavior.
No matter what value the method is set, it is cleared when the corresponding resource is used Targets It's always a good practice. Clear target permission Glide Maximize resource reuse, minimize memory overhead, and minimize unexpected behavior caused by edge conditions. If you use RequestManager#clear(Target),call Bitmap#recycle()Or mutation Bitmap Not only is it unsafe, it is also completely unnecessary and should be avoided. In all cases, priority RequestManager#clear(Target)instead of Bitmap#recycle(). 
  // Public API.
  @SuppressWarnings("unused")
  @NonNull
  public GlideBuilder setIsActiveResourceRetentionAllowed(
. . . 
/**
   * Adds a global {@link RequestListener} that will be added to every request started with Glide.
   *
   * <p>Multiple {@link RequestListener}s can be added here, in {@link RequestManager} scopes or to
   * individual {@link RequestBuilder}s. {@link RequestListener}s are called in the order they're
   * added. Even if an earlier {@link RequestListener} returns {@code true} from {@link
   * RequestListener#onLoadFailed(GlideException, Object, Target, boolean)} or {@link
   * RequestListener#onResourceReady(Object, Object, Target, DataSource, boolean)}, it will not
   * prevent subsequent {@link RequestListener}s from being called.
   *
   * <p>Because Glide requests can be started for any number of individual resource types, any
   * listener added here has to accept any generic resource type in {@link
   * RequestListener#onResourceReady(Object, Object, Target, DataSource, boolean)}. If you must base
   * the behavior of the listener on the resource type, you will need to use {@code instanceof} to
   * do so. It's not safe to cast resource types without first checking with {@code instanceof}.
   */
   Add a global RequestListener,Will be added to each Glide Request to start. Can be in RequestManager Add multiple in scope RequestListener,You can also add to a separate RequestBuilder Yes. RequestListener The call order of is in the order of addition. Even previous RequestListener from RequestListener#onLoadFailed(GlideException, Object, Target, boolean)or RequestListener#onResourceReady(Object, Object, Target, DataSource, boolean)return true,It won't stop the follow-up RequestListener Called. because Glide Requests can be initiated for any number of individual resource types, so any listener added here must accept them RequestListener#Any generic resource type (Object, Object, Target, DataSource, boolean) in onResourceReady. If you must base the listener's behavior on the resource type, you will need to use instanceof to do this. It is not safe to cast a resource type without first using the instanceof check.
  @NonNull
  public GlideBuilder addGlobalRequestListener(@NonNull RequestListener<Object> listener) {
. . . 
 /**
   * Set to {@code true} to make Glide populate {@link
   * com.bumptech.glide.load.engine.GlideException#setOrigin(Exception)} for failed requests.
   *
   * <p>The exception set by this method is not printed by {@link GlideException} and can only be
   * viewed via a {@link RequestListener} that reads the field via {@link
   * GlideException#getOrigin()}.
   *
   * <p>This is an experimental API that may be removed in the future.
   */
Set to true send Glide Populate for failed requests GlideException.setOrigin(Exception). 
Exceptions set by this method will not be ignored GlideException Print out, only through RequestListener adopt GlideException. getorigin()Read the fields to view.

This is an experimental study API,It may be deleted in the future.
  public GlideBuilder setLogRequestOrigins(boolean isEnabled) {
. . . 
Set to true to make Glide use ImageDecoder when decoding Bitmaps on Android P and higher.
Calls to this method on versions of Android less than Q are ignored. Although ImageDecoder was added in Android O a bug prevents it from scaling images with exif orientations until Q. See b/136096254.

Specifically ImageDecoder will be used in place of Downsampler and BitmapFactory to decode Bitmaps. GIFs, resources, and all other types of Drawables are not affected by this flag.

This flag is experimental and may be removed without deprecation in a future version.

When this flag is enabled, Bitmap's will not be re-used when decoding images, though they may still be used as part of Transformations because ImageDecoder does not support Bitmap re-use.

When this flag is enabled Downsampler.FIX_BITMAP_SIZE_TO_REQUESTED_DIMENSIONS is ignored. All other Downsampler flags are obeyed, although there may be subtle behavior differences because many options are subject to the whims of BitmapFactory and ImageDecoder which may not agree.
Set to true,send Glide use ImageDecoder When decoding bitmaps, in Android P Or higher.
In less than Q of Android Calls to this method will be ignored. although ImageDecoder stay Android O Added a bug,Prevent it from using exif Scale the image in the direction until q. 

especially ImageDecoder Will be used instead Downsampler and BitmapFactory To decode bitmap. gif,Resources and all other types of paintable objects are not affected by this flag.

The logo is experimental and may be removed without objection in future versions.

When this flag is enabled, Bitmap Will not be reused when decoding images, although they may still be used as part of the conversion because ImageDecoder I won't support it Bitmap Reuse of.

When this flag is enabled, Downsampler. FIX_BITMAP_SIZE_TO_REQUESTED_DIMENSIONS Ignored. All other Downsampler Signs are obedient, although there may be subtle behavioral differences, as many options are subject to BitmapFactory and ImageDecoder The effect of may not work.
  public GlideBuilder setImageDecoderEnabledForBitmaps(boolean isEnabled) {
. . . 

Subtotal

GlideBuilder is the core of building Glide objects. The main business process starts from here. Understanding the Glide construction configuration can better understand the subsequent application configuration and network configuration.
Its design concept contains a lot of good practice.

  • Memory optimization: bitmapPool, arrayPool, memoryCache;
  • Buffer Optimization: memoryCache, diskCacheFactory.
  • CPU execution: sourceExecutor, diskCacheExecutor, memorySizeCalculator, animationExecutor;
  • Network optimization: connectionitymonitorfactory, defaultRequestOptionsFactory, requestManagerFactory

The later analysis of Glide algorithm mainly focuses on the above aspects. In line with the principle of use. I will also summarize the forms that can be used for your use. Because it does not involve specific business, it may not be directly used in the project. But the key part and its structure depend on the readers to consider whether it is applicable.

A little feeling

When using Glide five or six years ago, I felt that such a line should not be too complicated. It was not until I tried to analyze and record from the design pattern that I found the brilliance and power.
I chose to analyze Glide open source project because I didn't think it would be too difficult, so I wrote a few articles to brush the sense of existence. But after going deep, I found the difficulty of leaving the complexity to myself and giving the concise use to users and visitors. I will also be in awe. Try my best to write down the structure of design optimization and adaptation.
Please also consider the user's perspective and user environment in the initial design and implementation process. Don't forget the original intention to write more wow functional modules. come on.

Appendix 1 description of relevant classes

com.bumptech.glide.load.engine.cache.MemoryCache

An interface for adding and removing resources from an in memory
cache.

Interface for adding and removing resources from the in memory cache.

com.bumptech.glide.load.engine.Resource

/** *A resource interface that wraps a particular type so that it
can be pooled and reused.
@param The type of resource wrapped by this class. */

A resource interface that wraps a specific type so that it can be shared and reused.
Parameter: wrapperable resource class

com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool

An interface for a pool that allows users to reuse {@link
android.graphics.Bitmap} objects.

An interface that allows users to reuse Bitmap objects.

com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool

Interface for an array pool that pools arrays of different types.

An array pool interface that stores pools of different types of arrays

com.bumptech.glide.load.engine.cache.DiskCache.Factory

An interface for lazily creating a disk cache.

The interface function delays the creation of disk cache

com.bumptech.glide.load.engine.cache.DiskCache

An interface for writing to and reading from a disk cache.

An interface that writes and reads data from the disk cache.

com.bumptech.glide.load.engine.executor.GlideExecutor

A prioritized {@link ThreadPoolExecutor} for running jobs in Glide.

In Glide, customize the thread pool and thread executor for priority tasks

com.bumptech.glide.load.resource.gif.GifDrawable

An animated {@link android.graphics.drawable.Drawable} that plays the
frames of an animated GIF.

Play the animation Drawable of GIF animation frame.

com.bumptech.glide.request.RequestOptions

/** * Provides type independent options to customize loads with
Glide. * *

Non-final to allow Glide's generated classes to be
assignable to their non-generated * equivalents. */
@SuppressWarnings("PMD.UseUtilityClass")

Glide provides type independent options for customizing loading policies
Non final allows Glide generated classes to be assigned to their non generated classes.

com.bumptech.glide.request.BaseRequestOptions

/**
 * A base object to allow method sharing between {@link RequestOptions} and {@link
 * com.bumptech.glide.RequestBuilder}.
 *
 * <p>This class is not meant for general use and may change at any time.
 *
 * @param <T> The particular child implementation
 */

A base object that allows method sharing between RequestOptions and RequestBuilder.
This class is not commonly used and may be changed at any time
Specific sub implementations

com.bumptech.glide.Glide.RequestOptionsFactory

/** Creates a new instance of {@link RequestOptions}. */

Create a new RequestOptions instance

com.bumptech.glide.RequestBuilder

/**  
* A generic class that can handle setting options and staring loads for generic resource types.  
* 
 @param <TranscodeType> The type of resource that will be delivered to the {@link  
 *     com.bumptech.glide.request.target.Target}. 
  */

A generic class that can handle setting options and starting loading of generic resource types
The resource type to which the parameter will be delivered to the target

com.bumptech.glide.load.engine.cache.MemorySizeCalculator

/**
 * A calculator that tries to intelligently determine cache sizes for a given device based on some
 * constants and the devices screen density, width, and height.
 */

A calculator attempts to intelligently determine the cache size for a given device based on some constants and device screen density, width and height.

com.bumptech.glide.manager.ConnectivityMonitorFactory

/**
 * A factory class that produces a functional {@link
 * com.bumptech.glide.manager.ConnectivityMonitor}.
 */

A factory class that generates a functional ConnectivityMonitor.

com.bumptech.glide.RequestManager

/**
 * A class for managing and starting requests for Glide. Can use activity, fragment and connectivity
 * lifecycle events to intelligently stop, start, and restart requests. Retrieve either by
 * instantiating a new object, or to take advantage built in Activity and Fragment lifecycle
 * handling, use the static Glide.load methods with your Fragment or Activity.
 *
 * @see Glide#with(android.app.Activity)
 * @see Glide#with(androidx.fragment.app.FragmentActivity)
 * @see Glide#with(android.app.Fragment)
 * @see Glide#with(androidx.fragment.app.Fragment)
 * @see Glide#with(Context)
 */

A course to manage and start Glide requests. You can use Activity, Fragment, and connection lifecycle events to intelligently stop, start, and restart requests. Obtain by instantiating a new object, or use the built-in Activity and Fragment life cycle processing to use the static Glide. Load method with your Fragment or Activity.

com.bumptech.glide.manager.DefaultConnectivityMonitorFactory

/**
 * A factory class that produces a functional {@link com.bumptech.glide.manager.ConnectivityMonitor}
 * if the application has the {@code android.permission.ACCESS_NETWORK_STATE} permission and a no-op
 * non functional {@link com.bumptech.glide.manager.ConnectivityMonitor} if the app does not have
 * the required permission.
 */

A factory class, if the application has ACCESS_NETWORK_STATE permission, which will generate a functional connectivity monitor; If the application does not have the necessary permissions, it generates a non functional connectivity monitor without operation.

com.bumptech.glide.manager.ConnectivityMonitor

An interface for monitoring network connectivity events.

Interface to monitor network connection events.

com.bumptech.glide.request.target.Target

/**
 * An interface that Glide can load a resource into and notify of relevant lifecycle events during a
 * load.
 *
 * <p>The lifecycle events in this class are as follows:
 *
 * <ul>
 *   <li>onLoadStarted
 *   <li>onResourceReady
 *   <li>onLoadCleared
 *   <li>onLoadFailed
 * </ul>
 *
 * The typical lifecycle is onLoadStarted -> onResourceReady or onLoadFailed -> onLoadCleared.
 * However, there are no guarantees. onLoadStarted may not be called if the resource is in memory or
 * if the load will fail because of a null model object. onLoadCleared similarly may never be called
 * if the target is never cleared. See the docs for the individual methods for details.
 *
 * @param <R> The type of resource the target can display.
 */

An interface into which Glide can load resources and notify related lifecycle events during loading.
The life cycle events in this class are as follows:
onLoadStarted
onResourceReady
onLoadCleared
onLoadFailed

A typical lifecycle is onloadstarted - > onresourceready or onloadfailed - > onloadcleared.
However, this is not guaranteed. onLoadStarted may not be called if the resource is in memory or the load fails due to an empty model object. Similarly, onLoadCleared may never be called if the target has never been cleared. Refer to the documentation for details on specific methods.

  • @The type of resource that the param target can display.

com.bumptech.glide.request.RequestListener

/**
 * A class for monitoring the status of a request while images load.
 *
 * <p>All methods in this interface will be called from a background thread if the {@code
 * RequestListener} is added to a request that is started with {@link RequestBuilder#submit()},
 * {@link RequestBuilder#submit(int, int)}, or {@link RequestBuilder#into(int, int)}. Those methods
 * no longer post results back to the main thread to avoid the unnecessary thread interactions and
 * corresponding latency. As a side affect though, listeners added to those requests are no longer
 * called on the main thread. {@code RequestListeners} added to requests started with {@link
 * RequestBuilder#into(Target)} or {@link RequestBuilder#into(ImageView)} will continue to be called
 * back on the main thread.
 *
 * @param <R> The type of resource being loaded.
 */

A class that monitors the status of requests when images are loaded.

If RequestListener is added to the request submitted by RequestBuilder#submit(), RequestBuilder#submit(int, int) or RequestBuilder#submit(int, int) or RequestBuilder#into(int, int), all methods in this interface will be called from the background thread. These methods no longer publish the results back to the main thread to avoid unnecessary thread interaction and corresponding delays. However, as a side effect, listeners added to these requests are no longer called on the main thread. Requests that RequestListeners add to RequestBuilder#into(Target) or RequestBuilder#into(ImageView) will continue to be called on the main thread.

@param the type of resource being loaded.

Appendix 2

com.bumptech.glide.load.engine.GlideException extends Exception

/** An exception with zero or more causes indicating why a load in Glide failed. */

An exception, zero or more reasons indicate why the Glide load failed

Keywords: Design Pattern Interview OOP Singleton pattern

Added by Ryan0r on Tue, 04 Jan 2022 08:39:09 +0200