我正在编写一个具有绘图功能的Android应用程序,并允许用户选择不同的画笔进行绘制。有一次,当笔刷改变时,我有以下方法:

public Brush newBrush(String className){
    Brush currentBrush;
    switch (className){
        case "StandardBrush":
            currentBrush = new StandardBrush(currentColor, currentSize);
            break;
        case "SquareBrush":
            currentBrush = new SquareBrush(currentColor, currentSize);
            break;
        case "Highlighter":
            currentBrush = new Highlighter(currentColor, currentSize);
            break;
        case "AirBrush":
            currentBrush = new AirBrush(currentColor, currentSize);
            break;
        case "PaintBrush":
            currentBrush = new PaintBrush(currentColor, currentSize);
            break;
        case "CalligraphicBrush":
            currentBrush = new CalligraphicBrush(currentColor, currentSize);
            break;
        case "VanishingBrush":
            currentBrush = new VanishingBrush(currentColor, currentSize);
            break
    }
    return currentBrush;
}


如果以后选择添加更多选项,则此switch语句可能会很长。那么有什么办法可以缩短它?例如将字符串转换为Class,然后仅创建该类的新实例?

最佳答案

这可能会降低性能,但是您可以使用反射。
就像是:

 return Class.forName(className).getConstructors()[0].newInstance(color, size);

08-26 00:38