BlackBerry:使我的图像线程类可用于所有实例

时间:2011-12-31 02:48:02

标签: blackberry java-me

我创建了一个图像线程类,它在正在加载图像的实例中运行update方法:

public class ImageThread implements Runnable {
    private Bitmap image;
    private String url;
    private CustomEventField c;


    public ImageThread(String url, CustomEventField c){

        this.url = url;
        this.c = c;
    }

   public void notifyUs(){



        this.c.update(image);
    }

    public void run() {

        Bitmap img =  downloadImage.connectServerForImage(this.url); //data processing

        image = img;

        notifyUs();

    }




}

我在构造函数中发送上下文,但是我只能将它用于CustomEventField。如果我想将此图像类用于其他类,该怎么办?我可以制作这个课程的另一个副本,但我想让事情井然有序。

2 个答案:

答案 0 :(得分:2)

定义一个单独的接口类型,然后所有类可以根据需要实现,例如:

ImageThreadCallback.java:

public interface ImageThreadCallback
{
    void update(Bitmap image);
}

ImageThread.java:

public class ImageThread implements Runnable
{
    private Bitmap image;
    private String url;
    private ImageThreadCallback c;

    public ImageThread(String url, ImageThreadCallback c)
    {
        this.url = url;
        this.c = c;
    }

    public void notifyUs()
    {
        this.c.update(this.image);
    }

    public void run()
    {
        this.image = downloadImage.connectServerForImage(this.url); //data processing
        notifyUs();
    }
}

CustomEventField.java:

public class CustomEventField implements ImageThreadCallback
{
    public void update(Bitmap image)
    {
        ...
    }
}

CustomEntryField.java:

public class CustomEntryField implements ImageThreadCallback
{
    public void update(Bitmap image)
    {
        ...
    }
}

答案 1 :(得分:0)

首先,ImageThread可能应该扩展Thread或重命名为ImageUpdateTask。

正如您在问题中提到的那样,难以重复使用的原因是因为它过于强烈耦合。这可以通过抽象方法来分离接口来解决。

public interface Receiver<T> {
    public void pass(T t);
}

-

public class ImageThread extends Thread {
    private Bitmap image;
    private final String url;
    private final Receiver<Bitmap> updater;

    public ImageThread(String url, Receiver<Bitmap> updater) {
        this.url = url;
        this.updater = updater;
    }

    @Override
    public void run() {
        Bitmap img =  downloadImage.connectServerForImage(this.url);
        //data processing

        image = img;
        updater.pass(image);
    }
}

-

public class CustomEventFieldUpdater implements Receiver<Bitmap> {
    @Override
    public void pass(Bitmap image) {
    //TODO
    }
}

-

public class CustomEntryFieldUpdater implements Receiver<Bitmap> {
    @Override
    public void pass(Bitmap image) {
    //TODO
    }
}