Java 怎么使用工厂方法模式创建类的实例

2019年7月18日21:09:11 评论 68

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;
  }
}

 

3.总结

示例代码演示了 Java 怎么使用工厂方法模式创建类的实例,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: