【发布时间】:2017-10-23 13:47:44
【问题描述】:
我尝试学习 Spring 框架。我有一些问题。
-
我创建了一个控制器和几个类。这是控制器:
@Controller @RequestMapping("/man") public class manController { private SwordImp Sword = new SwordImp(); private GunImp Gun = new GunImp(); private String mainWeapon; private String subWeapon; @RequestMapping(value = "set/{weapon:[a-z A-Z 0-9]+}", method = RequestMethod.GET) public String setWeapon(@PathVariable String weapon, Model model){ System.out.println(weapon); if(weapon.equals("gun")){ Gun.set(weapon); mainWeapon = Gun.getWeapon(); subWeapon = Gun.getSubWeapon(); }else{ if(weapon.equals("sword")){ Sword.set(weapon); mainWeapon = Sword.getWeapon(); subWeapon = Sword.getSubWeapon(); }else{ mainWeapon = "no weapon"; subWeapon = "no sub weapon"; } } model.addAttribute("weapon_status", mainWeapon); model.addAttribute("sub_weapon_status", subWeapon); return "man/index"; } } -
我还创建了一些类。
武器界面
public interface Weapon { public void set(String weaponName); public String getWeapon(); public String getSubWeapon(); }剑类
public class SwordImp implements Weapon { private String weaponName = null; public void set(String weapon) { this.weaponName = "fire "+weapon; } public String getWeapon() { return this.weaponName; } public String getSubWeapon() { return "no sub weapon"; } }枪类
public class GunImp implements Weapon { private String weaponName = null; private String bullet = null; public void set(String weapon) { this.weaponName = "ice "+weapon; this.bullet = "need bullet"; } public String getWeapon() { return this.weaponName; } public String getSubWeapon() { return this.bullet; } }
我的问题:
-
如果我没有在下面的gun类和sword类中实现Weapon类,好像这个功能还是可以工作的……那为什么还要使用接口呢?
剑类
public class SwordImp {...}枪类
public class GunImp {...} 我尝试将所有类放入存储库文件夹。这是正确的路径吗?还是我需要将它们放入模型文件夹中?
-
一开始,我尝试将Gun类和Sword类中的武器名称变量和子弹变量放入武器接口中,这样我就不需要在每个类中都声明它们了,像这样:
武器界面
public interface Weapon { private String weaponName = null; private String bullet = null; public void set(String weaponName); public String getWeapon(); public String getSubWeapon(); }剑类
public class SwordImp implements Weapon { public void set(String weapon) { this.weaponName = "fire "+weapon; this.bullet = "no sub weapon"; } public String getWeapon() { return this.weaponName; } public String getSubWeapon() { return this.bullet; } }枪类
public class GunImp implements Weapon { public void set(String weapon) { this.weaponName = "ice "+weapon; this.bullet = "need bullet"; } public String getWeapon() { return this.weaponName; } public String getSubWeapon() { return this.bullet; } }
但这似乎是错误的......原因是什么?
【问题讨论】:
-
请阅读一些关于 OOP 的理论。您对类和接口的理解似乎非常有限,因此关于设计模式的理论讨论毫无意义。
-
我认为阅读一些 OOP 和控制反转 IOC 对您很有用,我认为了解接口使用的最好方法是学习一些设计模式
标签: java spring spring-mvc