Skip to content

Instantly share code, notes, and snippets.

@up1
Created April 27, 2026 05:02
Show Gist options
  • Select an option

  • Save up1/290029909e8b7c98b994c8b49253923c to your computer and use it in GitHub Desktop.

Select an option

Save up1/290029909e8b7c98b994c8b49253923c to your computer and use it in GitHub Desktop.
Demo with SOLID principle

Demo with SOLID principle

  • SRP(Single Responsibility Principle)
  • OCP(Open/Closed Principle)
  • DIP(Dependency Inversion Principle)

Step 1 :: Order Processing with SRP

// Logic for holding order data
public class Order {
    private String orderId;
    private double amount;
    // Getters and Setters
}

// Responsibility: Database operations
public class OrderRepository {
    public void save(Order order) {
        System.out.println("Saving order " + order.getOrderId() + " to Database.");
    }
}

// Responsibility: Notifications
public class NotificationService {
    public void sendEmail(Order order) {
        System.out.println("Sending confirmation email for order " + order.getOrderId());
    }
}

Step 2 :: Discount strategy with OCP

  • Software entities should be open for extension, but closed for modification

Interface

public interface DiscountStrategy {
    double applyDiscount(double amount);
}

Implementations

public class BlackFridayDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double amount) {
        return amount * 0.5; // 50% off
    }
}

public class NoDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double amount) {
        return amount;
    }
}

Step 3 :: Integrate with Order processing

  • DIP
public class OrderService {
    private final OrderRepository repository;
    private final NotificationService notification;

    public OrderService(OrderRepository repository, NotificationService notification) {
        this.repository = repository;
        this.notification = notification;
    }

    public void processOrder(Order order, DiscountStrategy discountStrategy) {
        // Calculate total using OCP
        double finalPrice = discountStrategy.applyDiscount(order.getAmount());
        System.out.println("Final Price after discount: $" + finalPrice);

        // Save and Notify using SRP
        repository.save(order);
        notification.sendEmail(order);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment