设计模式

使用观察者模式设计下载器,View为观察者监听被观察者Download,当被观察者的状态发生改变时通知观察者

uml

监听器接口

public interface DownloadListener{
    beforeConnected(){
    }

    afterConnected(){
    }

    onProgress(){
    }

    onFinished(){
    }
}

Download

public class Download{
    String url;
    String path;
    DownloadListener l;
    int tag;

    Download(String url,DownloadListener l,int tag){

    }

    addHeader(){
    }
    setPath(){
    }
    setAppend(){
    }


    download(){
        l.beforeConnected();
        request();//请求网络
        l.connected();
        save();//保存文件
        l.finishied();
    }

     request(){
    }

    save(){
        ....
        onProgress();
        ....
    }

    pause(){
    }
    //`path`为空时调用此方法
    getDefaultPath(){
    }

}

DownloadRunnable

public class DownloadRunnable implements Runnable{

    public Download d;

    DownloadRunnable(Download d){
    }

    run(){
        d.download();
    }
}

DownloadsControl实现多任务下载以及开始/暂停控制

public class DownloadsControl{
    List<Download> list;
    ExecutorService executor;

    add(Downloads d){
        list.add(d);
    }

    start(int tag){
        findByTag()
        executor.execute(new DownloadRunnable(d));
    }

    pause(int tag){
        findByTag()
        d,pause();
    }

    remove(int tag){
        pause();
        list.remove();
    }

    getInfo(int tag){
    }
}

Activity监听Download的变化,在UI线程中更新View

public class MainActivity extends AppCompatActivity  {
    DownloadControl control;
    ListView listView;

    DownloadListener listener=new DownloadListener(){
        beforeConnected(){
        }

        afterConnected(){
            getLength();
        }

        onProgress(){
            //在UI线程更新View
            runOnUIThread();
            updateProgress();
        }

        onFinished(){
            if(pause){
                savedata();
            }
        }

    } ;

    onCreate(){
    }

    newDownlod(){
        d=new Download(url, listener, tag)
        control.add();
    }
    startDownload(){
        control.start();
    }

    pauseDownload(){
        control.pause();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值