Builder - Sam647254/Programetoj GitHub Wiki

Java

class Car {
  int wheel;
  String color;
  
  public Car(int wheel, String color) {
    this.wheel = wheel;
    this.color = color;
  }

  public String spec() {
    return "Wheels: " + wheel + ", color: " + color;
  }
}

class CarBuilder {
  int wheel;
  String color;

  public CarBuilder setWheel(int wheel) {
    this.wheel = wheel;
    return this;
  }

  public CarBuilder setColor(String color) {
      this.color = color;
      return this;
  }

  public Car getCar() {
    return new Car(wheel, color);
  }
}

// main
class Example {
  public static void main(String[] arguments) {
    var car = new CarBuilder().setWheel(4).setColor("Black").getCar();
    System.out.print(c);
  }
}

TypeScript

interface Car {
  wheel: number;
  color: string;
  spec: () => string;
}

interface CarConfiguration {
  wheel: number;
  color: string;
}

function makeCar({wheel, color}: CarConfiguration): Car {
  return {
    wheel,
    color,
    spec() {
      return `Wheels: ${wheels}, color: ${color}`;
    }
  };
}

// main
const car = makeCar({wheel: 4, color: "Black"});
console.log(car.spec());