// Builder
class MedicalReport {
private String patientName;
private String doctorName;
private List<String> tests;
private String diagnosis;
private String treatmentPlan;
private boolean isUrgent;
// Private constructor to force builder usage
private MedicalReport() {}
public void displayReport() {
[Link]("\n=== MEDICAL REPORT ===");
[Link]("Patient: " + patientName);
[Link]("Doctor: " + doctorName);
[Link]("Tests: " + [Link](", ", tests));
[Link]("Diagnosis: " + diagnosis);
[Link]("Treatment: " + treatmentPlan);
}
// Builder class
public static class Builder {
private MedicalReport report;
public Builder() {
report = new MedicalReport();
[Link] = new ArrayList<>(); // Initialize tests list
}
public Builder setPatientName(String name) {
[Link] = name;
return this;
}
public Builder setDoctorName(String name) {
[Link] = name;
return this;
}
}
public MedicalReport build() {
// Validate required fields
if ([Link] == null || [Link] == null)
{
throw new IllegalStateException("Patient and doctor names
are required");
}
// Set defaults if needed
if ([Link] == null) {
[Link] = "Pending diagnosis";
}
return report;
}
}
}
// Client code
public class BuilderPatternDemo {
public static void main(String[] args) {
// Build a standard report
MedicalReport standardReport = new [Link]()
.setPatientName("John Doe")
.setDoctorName("Dr. Smith")
.addTest("Blood test")
.addTest("X-ray")
.setDiagnosis("Common cold")
.setTreatmentPlan("Rest and hydration")
.build();
[Link]();
// Build an urgent report
MedicalReport urgentReport = new [Link]()
.setPatientName("Jane Smith")
.setDoctorName("Dr. Johnson")
.addTest("MRI scan")
.addTest("EEG")
.markAsUrgent()
.setDiagnosis("Possible concussion")
.setTreatmentPlan("Hospitalization required")
.build();
[Link]();
// Build a minimal report (with defaults)
MedicalReport minimalReport = new [Link]()
.setPatientName("Robert Brown")
.setDoctorName("Dr. Wilson")
.build();
[Link]();
}
}
Singleton
package Singleton;
import [Link];
import [Link];
import [Link];
public class DatabaseConnection {
private static DatabaseConnection instance;
private Connection connection;
private String url = "jdbc:mysql://localhost:3306/HospitalMS";
private String user = "root";
private String password = "";
private DatabaseConnection() {
try {
[Link]("[Link]");
[Link] = [Link](url, user,
password);
[Link]("Database connected successfully.");
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException("Failed to connect to the
database.", e);
}
}
public synchronized static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}
public Connection getConnection() {
return connection;
}
}
package Singleton;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class RegisterUser {
private static RegisterUser instance;
private Connection connection;
private RegisterUser() {
try {
connection =
[Link]().getConnection();
[Link]("✅ RegisterUser: Database connected.");
} catch (Exception e) {
[Link]("❌ Failed to connect to DB.");
[Link]();
}
}
public static RegisterUser getInstance() {
if (instance == null) {
instance = new RegisterUser();
}
return instance;
}
public void register(String username, String password, String role) {
try {
String hashedPassword = hashPassword(password);
String sql = "INSERT INTO user (username, password, role)
VALUES (?, ?, ?)";
try (PreparedStatement ps = [Link](sql))
{
[Link](1, username);
[Link](2, hashedPassword);
[Link](3, role);
[Link]();
[Link]("✅ User registered successfully.");
}
} catch (SQLException e) {
[Link]("❌ Error during registration.");
[Link]();
}
}
private String hashPassword(String password) {
try {
MessageDigest md = [Link]("SHA-256");
byte[] hashedBytes = [Link]([Link]());
StringBuilder hexString = new StringBuilder();
for (byte b : hashedBytes) {
[Link]([Link]("%02x", b));
}
return [Link]();
} catch (NoSuchAlgorithmException e) {
[Link]("❌ Error hashing password.");
[Link]();
return null;
}
}
}
package Singleton;
import [Link].*;
public class ReportGenerateDB {
private static ReportGenerateDB instance;
private Connection connection;
private ReportGenerateDB() {
try {
// Reusing the existing database connection
connection =
[Link]().getConnection();
} catch (Exception e) {
[Link]("❌ Failed to connect to the database.");
[Link]();
}
}
public synchronized static ReportGenerateDB getInstance() {
if (instance == null) {
instance = new ReportGenerateDB();
}
return instance;
}
public void generateReport() {
String sql = "SELECT username, role FROM user";
try (Statement stmt = [Link]();
ResultSet rs = [Link](sql)) {
[Link]("📊 Report: List of Users");
[Link]("----------------------------");
while ([Link]()) {
String username = [Link]("username");
String role = [Link]("role");
[Link]("Username: " + username + ", Role: " +
role);
}
[Link]("----------------------------");
[Link]("Report generated successfully.");
} catch (SQLException e) {
[Link]("❌ Error generating report.");
[Link]();
}
}
}
package Singleton;
import [Link];
public class Main {
public static void main(String[] args) {
// Register an admin user
Scanner scanner = new Scanner([Link]);
[Link]("Enter username: ");
String username = [Link]();
[Link]("Enter password: ");
String password = [Link]();
[Link]("Enter role: ");
String role = [Link]();
[Link]().register(username, password, role);
// Generate a sample report
ReportGenerateDB report = [Link]();
[Link]();
}
}
package Singleton;
public class ReportMain {
public static void main(String[] args) {
[Link]().generateReport();
}
}
package Singleton;
import [Link];
public class RegisterMain {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter username: ");
String username = [Link]();
[Link]("Enter password: ");
String password = [Link]();
[Link]("Enter role: ");
String role = [Link]();
[Link]().register(username, password, role);
}
}
Apdater
Here’s the minimal, essential implementation of the Adapter Pattern
with only the key
functions (no extra fluff):
1. [Link] (Adaptee)
java
Copy
Download
public class StockDataXML {
private String xml;
public StockDataXML(String xml) {
[Link] = xml;
}
public String getXml() {
return xml; // Key: Provides raw XML data
}
}
2. [Link] (3rd-Party Library)
java
Copy
Download
public class AnalyticsTool {
public void analyze(String jsonData) {
[Link]("Analyzing JSON: " + jsonData); // Key: Target
method (needs JSON)
}
}
3. [Link] (Adapter)
java
Copy
Download
public class XMLToJSONAdapter {
private StockDataXML xmlData;
public XMLToJSONAdapter(StockDataXML xmlData) {
[Link] = xmlData;
}
public void analyze() {
// Key: Conversion logic (XML → JSON)
String json = [Link]()
.replace("<stock>", "{").replace("</stock>", "}")
.replace("<", "\"").replace(">", "\"");
new AnalyticsTool().analyze(json); // Delegates to the target
}
}
4. [Link] (Client)
java
Copy
Download
public class Main {
public static void main(String[] args) {
String xml =
"<stock><symbol>AAPL</symbol><price>150.23</price></stock>";
StockDataXML xmlData = new StockDataXML(xml);
XMLToJSONAdapter adapter = new XMLToJSONAdapter(xmlData);
[Link](); // Key: Client only interacts with the Adapter
}
}
package address;
// Interface (Target)
public interface AddressValidator {
boolean isValidAddress(String inp_address, String inp_zip, String
inp_state);
}
package address;
public class CAAddress {
public boolean isValidCanadianAddr(String inp_address, String
inp_pcode, String inp_prvnc) {
return inp_address.trim().length() >= 15 &&
inp_pcode.trim().length() == 6 &&
inp_prvnc.trim().length() >= 6;
}
}
package address;
import [Link];
public class USAddress implements AddressValidator {
@Override
public boolean isValidAddress(String inp_address, String inp_zip,
String inp_state) {
return inp_address.trim().length() >= 10 &&
inp_zip.trim().length() >= 5 && inp_zip.trim().length() <=
10 &&
inp_state.trim().length() == 2;
}
}
package address;
import [Link];
import [Link];
public class CAAddressAdapter implements AddressValidator {
private CAAddress objCAAddress;
public CAAddressAdapter(CAAddress address) {
[Link] = address;
}
public boolean isValidAddress(String inp_address, String inp_zip,
String inp_state) {
return [Link](inp_address, inp_zip,
inp_state);
}
}
package address;
import [Link];
import [Link];
import [Link];
public class Customer {
public static final String US = "US";
public static final String CANADA = "Canada";
private String name;
private String address;
private String zip;
private String state;
private String type;
public Customer(String name, String address, String zip, String
state, String type) {
[Link] = name;
[Link] = address;
[Link] = zip;
[Link] = state;
[Link] = type;
}
public boolean isValidAddress() {
AddressValidator validator = getValidator(type);
return [Link](address, zip, state);
}
private AddressValidator getValidator(String custType) {
if ([Link](US)) {
return new USAddress();
} else if ([Link](CANADA)) {
return new CAAddressAdapter(new CAAddress());
}
throw new IllegalArgumentException("Unsupported customer type: "
+ custType);
}
}
package address;
import [Link];
public class TestValidation {
public static void main(String[] args) {
Customer usCustomer = new Customer("John", "123 Elm Street",
"12345", "NY", [Link]);
Customer caCustomer = new Customer("Pierre", "456 Bloor Street
West", "A1B2C3", "Ontario", [Link]);
[Link]("US Customer Address Valid: " +
[Link]());
[Link]("Canada Customer Address Valid: " +
[Link]());
}
}
package sms;
public class EmailNotificationService implements NotificationService {
@Override
public void sendMessage(String message, String to) {
[Link]("📧 Email sent to " + to + ": " + message);
}
}
package sms;
public class Notification {
public static void main(String[] args) {
// Email notification
NotificationService email = new EmailNotificationService();
[Link]("Hello There via Email", "nimo@[Link]");
// SMS notification via adapter
NotificationService sms = new SMSAdapter();
[Link]("Hey there via SMS", "0987654321");
}
}
package sms;
public interface NotificationService {
String message ="";
String to = "";
void sendMessage(String message, String to);
}
package sms;
public class SMSAdapter implements NotificationService {
private final SMSNotificationService smsService;
public SMSAdapter() {
[Link] = new SMSNotificationService();
}
@Override
public void sendMessage(String message, String to) {
// Adapting sendMessage to sendSMS
[Link](to, message);
}
}
package sms;
public class SMSNotificationService {
public void sendSMS(String number, String content) {
[Link]("? SMS sent to " + number + ": " + content);
}
}
package structuraldesign;
import [Link];
public class ImportTest {
public static void main(String[] args) {
LegacyCSVPatientSystem legacySystem = new
LegacyCSVPatientSystem();
LegacyPatientAdapter adapter = new
LegacyPatientAdapter(legacySystem);
List<Patient> patients = [Link]();
for (Patient p : patients) {
[Link]();
}
}
}
package structuraldesign;
public class LegacyCSVPatientSystem {
public String getLegacyData() {
return "P001,John Doe,1988-05-01\nP002,John Smith,1990-11-03";
}
}
package structuraldesign;
import [Link];
import [Link];
public class LegacyPatientAdapter {
private LegacyCSVPatientSystem legacySystem;
public LegacyPatientAdapter(LegacyCSVPatientSystem legacySystem) {
[Link] = legacySystem;
}
public List<Patient> getAdaptedPatients() {
List<Patient> patients = new ArrayList<>();
String data = [Link]();
String[] rows = [Link]("\n");
for (String row : rows) {
String[] fields = [Link]().split(",");
if ([Link] == 3) {
String id = fields[0].trim();
String name = fields[1].trim();
String dob = fields[2].trim();
[Link](new Patient(id, name, dob));
} else {
[Link]("️Skipped malformed row: " + row);
}
}
return patients;
}
}
package structuraldesign;
public class Patient {
private String id;
private String name;
private String dob;
public Patient(String id, String name, String dob) {
[Link] = id;
[Link] = name;
[Link] = dob;
}
public void display() {
[Link]("Patient ID: " + id + ", Name: " + name + ",
DOB: " + dob);
}
}
Factory Method Pattern (Single Product Hierarchy)
java
Copy
Download
// Product Interface
interface Doctor {
void diagnose();
// Concrete Products
class GeneralPractitioner implements Doctor {
public void diagnose() {
[Link]("General checkup and diagnosis");
}
}
class Neurologist implements Doctor {
public void diagnose() {
[Link]("Neurological examination");
}
public void treat() {
[Link]("Treating nervous system disorders");
}
}
// Creator Abstract Class
abstract class HospitalDepartment {
// Factory Method
public abstract Doctor createDoctor();
public void processPatient() {
Doctor doctor = createDoctor();
[Link]();
[Link]("----------");
}
}
// Concrete Creators
class GeneralMedicineDept extends HospitalDepartment {
public Doctor createDoctor() {
return new GeneralPractitioner();
}
}
class NeurologyDept extends HospitalDepartment {
public Doctor createDoctor() {
return new Neurologist();
}
}
// Client
public class FactoryMethodDemo {
public static void main(String[] args) {
HospitalDepartment general = new GeneralMedicineDept();
[Link]();
HospitalDepartment neuro = new NeurologyDept();
[Link]();
}
}
Abstract Factory Pattern (Multiple Product Families)
java
Copy
Download
// Abstract Products
interface Diagnosis {
void perform();
}
interface Treatment {
void administer();
}
// Cardiology Products
class CardiacDiagnosis implements Diagnosis {
public void perform() {
[Link]("Performing ECG and stress test");
}
}
class CardiacTreatment implements Treatment {
public void administer() {
[Link]("Prescribing beta blockers and statins");
}
}
// Neurology Products
class NeuroDiagnosis implements Diagnosis {
public void perform() {
[Link]("Conducting EEG and nerve tests");
}
}
class NeuroTreatment implements Treatment {
public void administer() {
[Link]("Administering neuropathic medications");
}
}
// Abstract Factory
interface MedicalDepartment {
Diagnosis createDiagnosis();
Treatment createTreatment();
}
// Concrete Factories
class CardiologyDept implements MedicalDepartment {
public Diagnosis createDiagnosis() {
return new CardiacDiagnosis();
}
public Treatment createTreatment() {
return new CardiacTreatment();
}
}
class NeurologyDept implements MedicalDepartment {
public Diagnosis createDiagnosis() {
return new NeuroDiagnosis();
}
public Treatment createTreatment() {
return new NeuroTreatment();
}
}
// Client
public class AbstractFactoryDemo {
public static void processPatient(MedicalDepartment dept) {
Diagnosis diag = [Link]();
Treatment treat = [Link]();
[Link]();
[Link]();
[Link]("==========");
}
public static void main(String[] args) {
processPatient(new CardiologyDept());
processPatient(new NeurologyDept());
}
}
Key Differences:
1. Factory Method:
o Creates a single product type (Doctor)
o Uses inheritance (subclasses implement factory method)
o Example: Different hospital departments creating their specific doctors
2. Abstract Factory:
o Creates families of related products (Diagnosis + Treatment)
o Uses composition (object contains factory methods)
o Example: Complete medical departments with matching diagnosis and
treatment protocols
When to Use Which:
Use Factory Method when you need to:
o Delegate object creation to subclasses
o Create a single type of product
o Want a simpler architecture
Use Abstract Factory when you need to:
o Create families of related products
o Ensure products are compatible
o Support multiple variants of a system
Both implementations are complete and runnable. The medical domain
examples show:
Factory Method: Different departments creating their specific doctors
Abstract Factory: Whole departments with coordinated diagnosis and
treatment approaches
import [Link];
import [Link];
// 1. Prototype Interface
interface MedicalTest extends Cloneable {
MedicalTest clone() throws CloneNotSupportedException; // THE key
method
void administer();
}
// 2. Concrete Prototype
class BloodTest implements MedicalTest {
private String patientName;
public MedicalTest clone() throws CloneNotSupportedException {
return (BloodTest) [Link](); // Shallow copy
}
public void administer() {
[Link]("Blood test for " + patientName);
}
public void setPatient(String name) {
[Link] = name;
}
}
// 3. Prototype Registry (Essential Manager)
class TestRegistry {
private static Map<String, MedicalTest> prototypes = new HashMap<>();
static {
[Link]("BLOOD", new BloodTest());
}
public static MedicalTest getTest(String type) throws
CloneNotSupportedException {
return [Link](type).clone(); // THE key operation
}
}
// 4. Client Usage
public class Main {
public static void main(String[] args) throws Exception {
MedicalTest test1 = [Link]("BLOOD");
[Link]();
MedicalTest test2 = [Link]("BLOOD");
[Link]("Same object? " + (test1 == test2)); // false
- different copies
}
}