This content originally appeared on DEV Community 👩💻👨💻 and was authored by Kerisnarendra
Visitor design pattern is a type of behavioral pattern, a way to separate an algorithm or an action from the objects it operates on. It allows new functionality to be added to a set of classes without modifying the classes themselves, by encapsulating the new functionality in a separate class called the Visitor. This makes it more flexible, maintainable and reusable.
This pattern can be used in a real-life vehicles service scenario to perform different inspections on a variety of vehicles.
This pattern consists of the following components:
- Visitor interface: it defines a visit method for each class in the object structure. Sample:
interface VehicleInspector {
visit(car: Car): void;
visit(van: Van): void;
visit(motorbike: Motorbike): void;
}
- Concrete visitor classes: it implements the visitor interface. Each concrete visitor class defines a specific behavior for the visit method. Sample:
class CarInspector implements VehicleInspector {
visit(car: Car): void {
console.log(`Visiting ${car.constructor.name} with CarInspector`);
}
}
class VanInspector implements VehicleInspector {
visit(van: Van): void {
console.log(`Visiting ${van.constructor.name} with VanInspector`);
}
}
class MotorbikeInspector implements VehicleInspector {
visit(motorbike: Motorbike): void {
console.log(`Visiting ${motorbike.constructor.name} with MotorbikeInspector`);
}
}
- Element interface: this defines an accept method that takes a visitor as a parameter. Sample:
interface Vehicle {
accept(vehicleInspector: VehicleInspector): void;
}
- Concrete element classes: it implements the element interface. Each concrete element class has an accept method that calls the appropriate visit method on the visitor for that class. Sample:
class Car implements Vehicle {
accept(vehicleInspector: VehicleInspector): void {
return vehicleInspector.visit(this)
}
}
class Van implements Vehicle {
accept(vehicleInspector: VehicleInspector): void {
return vehicleInspector.visit(this)
}
}
class Motorbike implements Vehicle {
accept(vehicleInspector: VehicleInspector): void {
return vehicleInspector.visit(this)
}
}
Sample to use:
let car = new Car();
let van = new Van();
let motorbike = new Motorbike();
let carInspector = new CarInspector();
car.accept(carInspector);
let vanInspector = new VanInspector();
van.accept(vanInspector);
let motorbikeInspector = new MotorbikeInspector();
motorbike.accept(motorbikeInspector);
This content originally appeared on DEV Community 👩💻👨💻 and was authored by Kerisnarendra
Kerisnarendra | Sciencx (2023-01-16T03:21:50+00:00) Visitor Pattern in Typescript. Retrieved from https://www.scien.cx/2023/01/16/visitor-pattern-in-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.