java – 根据用户输入确定构造函数调用

前端之家收集整理的这篇文章主要介绍了java – 根据用户输入确定构造函数调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要向用户询问他想绘制的图中有多少边,然后调用正确的构造函数来实例化该对象.

下面是我尝试使用IF语句来解决答案(或者我可以使用一个开关),但是我不知道这是否是最好的方法,可能是Java继承和多态.

所有的类都扩展了类图.

类别图:

  1. --------------- Figure ---------------
  2. ^ ^ ^ ^
  3. | | | |
  4. | | | |
  5. Circle Triangle Rectangle Exagone

主要类别:

  1. import java.util.Scanner;
  2.  
  3. class Draw {
  4.  
  5. static void main(String[] args){
  6.  
  7. Scanner userInput = new Scanner(System.in);
  8. int num_sides;
  9.  
  10. //user input
  11. System.out.println("How many sides has the figure you want to draw?");
  12. num_sides = userInput.nextInt();
  13.  
  14.  
  15. //---> deciding what constructor to call with if statements
  16.  
  17. if(num_sides == 0){
  18. Figure f1 = new Circle();
  19. }
  20. else if(num_sides == 3){
  21. Figure f1 = new Triangle();
  22. }
  23. //...
  24. else{
  25. System.out.println("Error. Invalid sides number");
  26. }
  27.  
  28.  
  29. }
  30. }

类别编号:

  1. class Figure{
  2.  
  3. private int sides;
  4.  
  5. public Figure(int num_sides){
  6. sides = num_sides;
  7. }
  8. }
  9.  
  10.  
  11. class Circle extends Figure{
  12.  
  13. public Circle(){
  14. super(0);
  15. }
  16.  
  17. }
  18.  
  19. //... all the other classes has the same structure of Circle

解决方法

工厂方法

你考虑过Factory Method Pattern吗?基本上,你有一个这样的方法

  1. public Figure createInstance(int numSides) {
  2. Figure figure = null;
  3.  
  4. switch(numSides) {
  5. case 0:
  6. figure = new Circle();
  7. break;
  8. case 3:
  9. // etc...
  10. // Make a case for each valid number of sides
  11. // Don't forget to put a "break;" after each case!
  12. default:
  13. // Not a valid shape; print your error message
  14. }
  15. return figure;
  16. }

而让这种工厂方法做出决定.

猜你在找的Java相关文章