模板模式:定义一个操作中的算法骨架,而将一些操作延迟到子类。模板方法使得子类可以不改变一个算法的结构,即可重定义该算法的某些特定步骤。
模式模式举例说明:
上述可以我们学习模板模式的动机来源于Glide,那我们就来模拟Glide定义不同的数据源模板来举例
1.)先定义下载抽象类AbstractImageLoader
public abstract class AbstractImageLoader { //抽象类定义整个流程骨架 public final void downloadImage(String imageUrl,int width,int height){ //先获取最终的数据源URL String finalImageUrl=getUrl(imageUrl,width,height); //然后开始执行下载 } //以下是不同子类根据自身特性完成的具体步骤 protected abstract String getUrl(String imageUrl,int width,int height); }
2.)具体类实现
WebpImageLoader
public class WebpImageLoader extends AbstractImageLoader { @Override protected String getUrl(String imageUrl, int width, int height) { return String.format("%s?imageView2/1/w/%d/h/%d/format/webp", imageUrl, width, height); } }
JpgImageLoader
public class JpgImageLoader extends AbstractImageLoader { @Override protected String getUrl(String imageUrl, int width, int height) { return String.format("%s?imageView2/1/w/%d/h/%d/format/jpg", imageUrl, width, height); } }
3.)具体使用
String imageUrl = "https://img-my.csdn.net/uploads/201309/01/1378037235_7476.jpg"; AbstractImageLoader loader =new WebpImageLoader(); loader.downloadImage(imageUrl,200,200);