I've done my first OOP project in Java. It is a project for my university course, it consists in a Logic Circuit Simulator with GUI. It works, but the problem is that the creation of a new different components is done using a switch case and my professor doesn't want me to use it. The code below runs when someone press the "Create" button on the GUI. The type "ComponenteLogico" is a superclass, and the classes "portaAND", "portaOR", "portaNAND" and company are all "ComponenteLogico" subclasses. How could I avoid the switch case? Sorry if I used a bad english
int inputs=jComboBox1.getSelectedIndex()+2;
ComponenteLogico comp=null;
if(jList1.getSelectedValue() == null)
{
System.out.println("Nessun componente creato");
System.out.println("prova1");
}//nel caso dell'aggiunta di una nuova classe bisogna aggiungere la voce corrispondente nello switch case sottostante
else switch (jList1.getSelectedValue()) {
case "AND":
{
comp= new portaAND(inputs);
break;
}
case "OR":
{
comp = new portaOR(inputs);
break;
}
case "NAND":
{
comp = new portaNAND(inputs);
break;
}
case "NOR":
{
comp = new portaNOR(inputs);
break;
}
You could try something along the lines of the command pattern/factory pattern: have a Map<String, Function<Integer, ComponentLogico>>
, populate it somewhere upon program start up (ie in a constructor):
class A {
private final Map<String, Function<Integer, ComponentLogico>> componentMap;
public A() {
componentMap = new HashMap<>();
// Lambda syntax
componentMap.put("AND", (inputs) -> new portaAND(inputs));
componentMap.put("OR", (inputs) -> new portaOR(inputs));
componentMap.put("NAND", (inputs) -> new portaNAND(inputs));
componentMap.put("NOR", (inputs) -> new portaNOR(inputs));
// Or use even more condensed syntax with method references:
componentMap.put("AND", portaAND::new);
componentMap.put("OR", portaOR::new);
componentMap.put("NAND", portaNAND::new);
componentMap.put("NOR", portaNOR::new);
}
public void something() {
...
String componentName = jList1.getSelectedValue();
if (!componentMap.contains(componentName)) {
// Invalid name (not in map)
}
ComponenteLogico comp = componentMap.get(jList1.getSelectedValue()).apply(inputs);
...
}
}
Notice, we effectively store the constructor to each type of ComponenteLogico
in a Map
, where we can get that constructor by using its name. We can then call this constructor as a Function<int, ComponenteLogico>
, which has a method ComponenteLogico apply(int value)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.