英文:
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论