Master Real-World Java Design Patterns!
Subscribe to Ram N Java for intuitive programming tutorials, behavioral design patterns, and practical Java architecture implementations!
🔔 Subscribe to Ram N JavaThe Scenario: A Doctor Visiting Different Patient Categories
Consider a healthcare system where various types of patients—such as children, adults, and senior citizens—need medical assessments. Each category of patient requires distinct checkup protocols, diagnostic tests, and dosage considerations.
If you hardcode checkup procedures directly into the patient classes, you quickly run into architectural bottlenecks. Whenever medical regulations update, or a new specialist (e.g., a dentist or cardiologist) visits the patient, you would be forced to open and modify every patient class, directly violating the Open/Closed Principle.
The Solution: Applying the Visitor Pattern
The Visitor Design Pattern separates medical assessment logic from the patient data models by utilizing Double Dispatch:
-
Visitable Element (Patient): Each patient class defines an
accept(Visitor visitor)method, passing itself to the visiting medical practitioner. -
Visitor Interface (Doctor): Declares specialized visit operations for each concrete patient type (e.g.,
visit(ChildPatient patient),visit(SeniorPatient patient)). - Concrete Visitor (GeneralPhysician / Specialist): Implements the specific medical assessment or treatment routines tailored to the specific patient type without altering the patient's internal structure.
Architectural Advantages in Practice
Using the Visitor pattern for domain modeling offers key architectural benefits:
- Open/Closed Principle: Introduce new doctors, health inspectors, or billing visitors without modifying existing patient classes.
- Single Responsibility Principle: Gathers related diagnostic and medical checkup operations into dedicated visitor classes instead of bloating data models.
- Extensible Operations: Easy to introduce new operations (like health index calculations or vaccination audits) across an entire group of patient objects.
Related Tutorials from Ram N Java
Click here to watch in Youtube : https://www.youtube.com/watch?v=P8ScJp-p1So
Click the below Image to Enlarge
| Visitor Design pattern - Implementation [Kids] |
| Visitor Design pattern - Implementation [Kids] - Class Diagram |
Visitable.java
{
private String name;
private String healthStatus;
public Child( String name )
{
super();
this.name = name;
}
public String getName()
{
return name;
}
public String getHealthStatus()
{
return healthStatus;
}
public void setHealthStatus( String healthStatus )
{
this.healthStatus = healthStatus;
}
@Override
public void accept( Visitor visitor )
{
visitor.visit(this);
}
}
No comments:
Post a Comment