对于Java枚举的我来说,这是不可能的。
为了接近您发布的代码段,您将很详细,正如您已经假设的那样。
枚举
enum BarcodeType {
UPCA,
QRCode,
UNDEFINED;
}
工厂类
abstract class Barcode {
abstract public BarcodeType getType();
public static final Barcode newUPCA(int numberSystem, int manufacturer, int product, int check) {
return new BarcodeUPCA(numberSystem, manufacturer, product, check);
}
public static final Barcode newQRCode(String productCode) {
return new BarcodeQRCode(productCode);
}
}
具体实施 UPCA
class BarcodeUPCA extends Barcode {
private final int numberSystem;
private final int manufacturer;
private final int product;
private final int check;
public BarcodeUPCA(int numberSystem, int manufacturer, int product, int check) {
this.numberSystem = numberSystem;
this.manufacturer = manufacturer;
this.product = product;
this.check = check;
}
public int getNumberSystem() {
return numberSystem;
}
public int getManufacturer() {
return manufacturer;
}
public int getProduct() {
return product;
}
public int getCheck() {
return check;
}
@Override
public BarcodeType getType() {
return BarcodeType.UPCA;
}
}
具体实现二维码
class BarcodeQRCode extends Barcode {
private final String productCode;
public BarcodeQRCode(String productCode) {
this.productCode = productCode;
}
public String getProductCode() {
return productCode;
}
@Override
public BarcodeType getType() {
return BarcodeType.QRCode;
}
}
演示应用程序
public class BarcodeMain {
public static void main(String[] args) throws Exception {
List<Barcode> barcodes = new ArrayList<>();
barcodes.add(Barcode.newUPCA(8, 85909, 51226, 3));
barcodes.add(Barcode.newQRCode("foobar"));
for (Barcode barcode : barcodes) {
switch (barcode.getType()) {
case UPCA: {
BarcodeUPCA b = (BarcodeUPCA) barcode;
System.out.printf("UPC-A: %d, %d, %d, %d%n",
b.getNumberSystem(),
b.getManufacturer(),
b.getProduct(),
b.getCheck()
);
break;
}
case QRCode: {
BarcodeQRCode b = (BarcodeQRCode) barcode;
System.out.printf("QR code: %s%n", b.getProductCode());
break;
}
default:
System.err.println("unhandled type: " + barcode.getType());
}
}
}
输出
UPC-A: 8, 85909, 51226, 3
QR code: foobar