1.简介
Java 怎么使用工厂方法模式创建类的实例?——请看下文。
2.示例代码
/**
* 版权所有 编程十万个怎么办(www.tah1986.com)
*/
class PlayerFactory {
public static Player createPlayer() {
Player returnType = new Player();
return returnType;
}
}
class Player {
private String firstName;
private String lastName;
private String position;
private int status = -1;
public Player() {
}
public Player(String position, int status) {
this.position = position;
this.status = status;
}
protected String playerStatus() {
String returnValue = null;
switch (getStatus()) {
case 0:
returnValue = "ACTIVE";
case 1:
returnValue = "INACTIVE";
case 2:
returnValue = "INJURY";
default:
returnValue = "ON_BENCH";
}
return returnValue;
}
public String playerString() {
return getFirstName() + " " + getLastName() + " - " + getPosition();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
if (firstName.length() > 30) {
this.firstName = firstName.substring(0, 29);
} else {
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
展开全文