有没有办法在多个方法中避免重复创建对象,而不在类级别上创建对象?

huangapple 未分类评论51阅读模式
英文:

Is there way to avoid repetative object creation in a multiple methods without creating object at class level

问题

public void benzCar(boolean car, List updateCarList) {
    if (car) {
        updateCarList.add(createCar("black"));
    }
}

public void audiCar(boolean car, List updateCarList) {
    if (car) {
        updateCarList.add(createCar("yellow"));
    }
}

public void fordCar(boolean car, List updateCarList) {
    if (car) {
        updateCarList.add(createCar("red"));
    }
}

private Object createCar(String color) {
    Object car = new Object();
    car.setCarColor(color);
    return car;
}

在每个方法中,都创建了一个新的对象,并使用该对象设置车辆的颜色(字符串)。除了在类级别创建对象之外,是否有任何方法可以避免在每个方法中重复创建对象。初学者在这里,提前致谢。

英文:
public void benzCar(boolean car,List updateCarList)
{
  if(car)
  {
    Object color=new Object();
    color.setCarColor("black");
    updateCarList.add(color);
  }
}

public void audiCar(boolean car,List updateCarList)
{
  if(car)
  {
    Object color=new Object();
    color.setCarColor("yellow");
    updateCarList.add(color);
  }
}

public void fordCar(boolean car,List updateCarList)
{
  if(car)
  {
    Object color=new Object();
    color.setCarColor("red");
    updateCarList.add(color);
  }
}

Here in every method a new object is being created and we are seting color(string) for car using that object.without creating object at class level,is there any way to avoid this repetative object creation in every method.Begineer here thanks in advance.

huangapple
  • 本文由 发表于 2020年5月4日 15:38:08
  • 转载请务必保留本文链接:https://java.coder-hub.com/61587264.html
匿名

发表评论

匿名网友

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

确定