Skip to content

Instantly share code, notes, and snippets.

@krohit-bkk
Last active January 13, 2024 17:47
Show Gist options
  • Save krohit-bkk/58f25e82b3264ae5f77637aefc134c79 to your computer and use it in GitHub Desktop.
Save krohit-bkk/58f25e82b3264ae5f77637aefc134c79 to your computer and use it in GitHub Desktop.
Example to demonstrate Open-Closed Principle
import java.util.ArrayList;
import java.util.List;
class Item {
private final String type;
private final double price;
private DiscountStrategy discountStrategy;
public Item(String type, double price, DiscountStrategy discountStrategy) {
this.type = type;
this.price = price;
this.discountStrategy = discountStrategy;
}
public String getType() {
return type;
}
public double getPrice() {
return price;
}
public DiscountStrategy getDiscountStrategy(){
return discountStrategy;
}
}
interface DiscountStrategy {
double applyDiscount(double price);
}
class BookDiscountStrategy implements DiscountStrategy {
@Override
public double applyDiscount(double price) {
return price * 0.9; // 10% discount on books
}
}
class ElectronicMarkupStrategy implements DiscountStrategy {
@Override
public double applyDiscount(double price) {
return price * 1.2; // 20% markup on electronics
}
}
class ShoppingCart {
private final List<Item> items;
public ShoppingCart(List<Item> items){
this.items = items;
}
public double calculateItemPrice(Item item) {
// Dynamic behaviour basis DiscountStrategy types
DiscountStrategy strategy = item.getDiscountStrategy();
return strategy.applyDiscount(item.getPrice());
}
public double calculateTotalPrice(){
double totalPrice = 0.0;
for(Item item: items)
totalPrice += calculateItemPrice(item);
return totalPrice;
}
}
public class Main {
public static void main(String[] args) {
// List of items
List<Item> items = new ArrayList<Item>();
// Creating Book items and discount
DiscountStrategy bookDiscount = new BookDiscountStrategy();
Item book = new Item("Book", 50.0, bookDiscount);
items.add(book);
// Creating Electronic items and discount
DiscountStrategy electronicStrategy = new ElectronicMarkupStrategy();
Item tv = new Item("Electronic", 100.0, electronicStrategy);
items.add(tv);
// Building a shopping cart
ShoppingCart shoppingCart = new ShoppingCart(items);
// Calculating total price for items
double totalPriceForBook = shoppingCart.calculateItemPrice(book);
double totalPriceForTv = shoppingCart.calculateItemPrice(tv);
double totalCartPrice = shoppingCart.calculateTotalPrice();
// Displaying results
System.out.println("Total Price for Book : $" + totalPriceForBook); // Should be 45
System.out.println("Total Price for TV : $" + totalPriceForTv); // Should be 120
System.out.println("Total Price entire cart : $" + totalCartPrice); // Should be 165
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment