如何允许用户在FilenameFilter中编写自己的预定义方法(如accept())的实现

时间:2011-11-01 14:43:21

标签: java design-patterns itext

FilenameFilter有一个accept方法,我可以用它来告诉系统我想要如何过滤文件。我想实现类似的东西。这是我的情景:

我正在编写一个在iText之上运行的通用API,它将Barcode添加到pdf文档中。我有一个通用的自定义条形码。

public class MyCustomBarcode{

/**
 * This variable holds the type of barcode
 * com.itextpdf.text.pdf.Barcode
 */
private Barcode barcode;

/**
 * The X position of the barcode. (0, 0) is at the bottom left
 */
private float x;

/**
 * The Y position of the barcode. (0, 0) is at the bottom left
 */
private float y;

/**
 * 
 */
private int rotation;

...
}

因此,当用户使用此API时,他们只需要将List<MyCustomBarcode>传递给我的API中的方法,然后API就会在每个pdf页面上插入条形码。问题是每个条形码都有不同的code格式。例如,BarcodeInter25可能会使用类似000001, 000002 ...的代码,其中Barcode39可能会使用其他内容。所以我想让用户自己编写如何生成条形码值的实现。像这样的东西

MyCustomBarcode barcode = new MyCustomBarcode(x, y, z){
    public String getSeqNum(int i){
       //The user own implementation of how they want integer i to look like.
       //E.g if i==1, I might return 000001
    }
);

由于我允许用户使用多种类型的条形码,我希望允许他们为每个条形码编写自己的实现。

1 个答案:

答案 0 :(得分:2)

在父类中,创建方法abstract,然后让每个子类提供自己的具体实现。


实施例

父类

public abstract class Barcode{
    .
    .
    .
    public abstract String getSeqNum(int i);
}

子类

public final class FooBarcode extends Barcode{
    .
    .
    .
    public final String getSeqNum(int i){
        // provide own implementation
    }
}