Implement an abstract factory that produces typed product instances
Implement the GoF creational pattern abstract factory. Define a base VehicleFactory whose create(type) method throws (it is abstract). Define a concrete CarFactory extends VehicleFactory whose create(type) returns a Sedan or Coupe instance (both subclasses of a Car base that stores this.type) and throws Error('Unknown car type') for anything else.
Requirement: callers depend only on the factory interface, never on concrete product constructors.
class VehicleFactory {
create(type) {
// your code here
}
}
Write the implementation.
Make the base create throw so the abstract class cannot be used directly. In CarFactory.create, switch on type: return new Sedan() or new Coupe(), else throw. Callers hold a VehicleFactory reference and call create, so swapping in another factory subclass changes the product family without touching the calling code.
- ✗Letting the base
createreturn something instead of throwing, so the abstract factory is callable directly - ✗Returning plain object literals instead of real
Sedan/Coupeinstances, losing the prototype chain andinstanceof - ✗Forgetting the
default/else branch, so an unknown type silently returnsundefinedinstead of throwing
- →How does depending on
VehicleFactoryrather thannew Sedan()make the calling code easier to extend? - →How would you add a second product family, say
TruckFactory, without changing existing callers?
Solution
The base class makes the method abstract via throw; the concrete factory branches on the type.
class Car {
constructor(type) {
this.type = type;
}
}
class Sedan extends Car {
constructor() {
super('Sedan');
}
}
class Coupe extends Car {
constructor() {
super('Coupe');
}
}
class VehicleFactory {
create(type) {
throw new Error('create() must be implemented by a subclass');
}
}
class CarFactory extends VehicleFactory {
create(type) {
switch (type) {
case 'Sedan':
return new Sedan();
case 'Coupe':
return new Coupe();
default:
throw new Error('Unknown car type');
}
}
}
const factory = new CarFactory();
const car = factory.create('Sedan'); // Car { type: 'Sedan' }
How it works
VehicleFactory defines the interface: a create method that the base class merely declares and immediately throws from. That makes it abstract — it cannot be used directly, you must subclass it.
CarFactory implements create, selecting the concrete product class by type. It returns real Sedan/Coupe instances, so instanceof Car works and the prototype chain is preserved. An unknown type hits the default branch and surfaces a clear error.
The key benefit: calling code holds a VehicleFactory-typed reference and calls create. Swapping in a TruckFactory changes the entire product family without touching the code that consumes the products. </content> </invoke>