------------翁恺老师授课
第五次课程 设计原则
课程核心部分体现在程序的优化中,从繁琐到简洁!!!
- 避免大量的代码复制
- 避免大量的if-else
- 类中成员变量请设置成私有访问属性
消除代码复制:
1.函数封装
System.out.println("你在" + currentRoom);
System.out.print("出口有: ");
if(currentRoom.northExit != null)
System.out.print("north ");
if(currentRoom.eastExit != null)
System.out.print("east ");
if(currentRoom.southExit != null)
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
----------------------------------
public void showPrompt(Room cRoom) {
System.out.println("现在你在" + cRoom);
System.out.print("出口有: ");
if(currentRoom.northExit != null)
System.out.print("north ");
if(currentRoom.eastExit != null)
System.out.print("east ");
if(currentRoom.southExit != null)
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
}
}
2.父类
代码的耦合与聚合
耦合:类与类之间应该保持距离,越远越好。
聚合:针对类与方法,与程序中一个单独的单元所承担的任务的数量和种类相对应有关。一个方法只负责一件定义明确的事情。
可扩展性
问题: 在程序中进行硬编码,很多类的硬编码是基于字符界面,通过终端进行输入输出。
解决方案: 从程序中识别出框架和数据,以代码实现框架,将部分功能以数据的方式加载(容器)。擅于使用容器来解决问题,实现灵活性。
public class Room {
public String description;
public Room northExit;
public Room southExit;
public Room eastExit;
public Room westExit;
public Room(String description)
{
this.description = description;
}
}
private void goRoom(String direction)
{
Room nextRoom = null;
if(direction.equals("north")) {
nextRoom = currentRoom.northExit;
}
if(direction.equals("east")) {
nextRoom = currentRoom.eastExit;
}
if(direction.equals("south")) {
nextRoom = currentRoom.southExit;
}
if(direction.equals("west")) {
nextRoom = currentRoom.westExit;
}
if (nextRoom == null) {
System.out.println("那里没有门!");
}
else {
currentRoom = nextRoom;
System.out.println("你在" + currentRoom);
System.out.print("出口有: ");
if(currentRoom.northExit != null)
System.out.print("north ");
if(currentRoom.eastExit != null)
System.out.print("east ");
if(currentRoom.southExit != null)
System.out.print("south ");
if(currentRoom.westExit != null)
System.out.print("west ");
System.out.println();
}
}
改造后
public class Room {
private String description;
private HashMap<String, Room> exits = new HashMap<String, Room>();
Public String getExits () {
StringBuffer sb = new StringBuffer();
for(String dir: exits.keySet()) {
sb.append(dir);
sb.append(' ');
}
return sb.toString();
}
public void showPrompt(Room cRoom) {
System.out.println("现在你在" + cRoom);
System.out.print("出口有: ");
------
String exits = cRoom.getExits();
System.out.println(exits);
-------
System.out.println();
}