Вместо того, чтобы избегать символов, которые могут вызвать проблемы в вашем регулярном выражении (например, черный список), почему бы вам не использовать вместо этого белый список. Таким образом, каждый символ считается испорченным, если он не соответствует.
В этом примере предположим следующее выражение:
RegExp.escape('be || ! be');
Это белый список букв, цифр и пробелов:
RegExp.escape = function (string) {
return string.replace(/([^\w\d\s])/gi, '\\$1');
}
Возвраты:
"be \|\| \! be"
Это может привести к тому, что символы не должны быть экранированы, но это не мешает вашему выражению (может быть, некоторые незначительные штрафные санкции), но это того стоит ).
Хотя я и согласен с замечаниями о том, что вопрос сформулирован недостаточно хорошо, я дам вам решение. Не стесняйтесь добавлять дженерики, чтобы сделать его более красивым.
public class Car {
static class CarConfig {
int x;
int y;
CarConfig(int x, int y) {
this.x = x;
this.y = y;
}
}
private final Engine engine;
public Car(int x, int y) {
this(new CarConfig(x, y));
}
Car(CarConfig config) {
this.engine = createEngine(config);
}
protected Engine createEngine(CarConfig config) {
return new Engine(config.x ,config.y);
}
}
Тогда в вашем подклассе:
public class FastEngine extends Engine {
public FastEngine(int x, int y, double a, double b) {
super(x, y);
// (...)
}
// (...)
}
public class FastCar extends Car {
static class FastCarConfig extends CarConfig {
double a;
double b;
FastCarConfig(int x, int y, double a, double b) {
super(x, y);
this.a = a;
this.b = b;
}
}
private final double a;
private final double b;
public FastCar(int x, int y, double a, double b) {
super(new FastCarConfig(x, y, a, b);
this.a = a;
this.b = b;
}
@Override
protected Engine createEngine(CarConfig config) {
if (config instanceof FastCarConfig) throw new IllegalStateException("You messed up!");
FastCarConfig c = (FastCarConfig) config;
return new FastEngine(c.x, c.y, c.a, c.b);
}
}
B O O M!
Предлагаю создать завод по производству двигателей. Помните принцип « Одиночной ответственности » ( ТВЕРДЫЙ ).
В реальной жизни вы не строите двигатель внутри автомобиля. Вы делаете это отдельно. Иногда на другом заводе. Двигатель устанавливается в машине на конвейере.
Это дает вам больше гибкости как на заводе, так и в коде.
В дальнейшем я предлагаю реализовать шаблон для строителей - если у вас в машине будет больше деталей.
P.s. игнорировать "статические" s - я просто добавил их, чтобы избежать предупреждений IDE.
public static void main(String[] args) {
Car car = new Car(EngineFactory.createEngine(1, 2));
Car fastCar = new FastCar(EngineFactory.createEngine(1, 2, 1d, 2d), 1d, 2d);
}
static class EngineFactory{
public static Engine createEngine(int x, int y){
return new Engine(x, y);
}
public static Engine createEngine(int x, int y, double a, double b){
return new FastEngine(x, y, a, b);
}
}
public static class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
}
public static class FastCar extends Car {
private final double a;
private final double b;
public FastCar(Engine engine, double a, double b) {
super(engine);
this.a = a;
this.b = b;
}
}
public static class FastEngine extends Engine {
public FastEngine(int x, int y, double a, double b) {
super(x, y);
}
}
public static class Engine{
int x;
int y;
public Engine(int x, int y) {
this.x = x;
this.y = y;
}
}
Верните конструкцию двигателя обратно в конструктор автомобиля. Если создание движков занимает больше, чем вызов конструктора, переместите его в статическую функцию конструктора.
class Engine {
private final int x;
private final int y;
Engine(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Car {
private final Engine engine;
public Car(int x, int y) {
this(new Engine(x, y));
}
Car(Engine engine) {
this.engine = engine;
}
}
public class FastEngine extends Engine {
private final double a;
private final double b;
FastEngine(int x, int y, double a, double b) {
super(x, y);
this.a = a;
this.b = b;
}
}
public class FastCar extends Car {
public FastCar(int x, int y, double a, double b) {
super(new FastEngine(x, y, a, b));
}
}