Skip to content

Instantly share code, notes, and snippets.

@kgsnipes
Last active January 29, 2024 03:20
Show Gist options
  • Save kgsnipes/ca3cead1a49447e840c977882c7d03e3 to your computer and use it in GitHub Desktop.
Save kgsnipes/ca3cead1a49447e840c977882c7d03e3 to your computer and use it in GitHub Desktop.
design patterns in Java
import java.util.*;
import java.util.function.Consumer;
public class DesignPatterns {
public static void main(String[] args) {
// Factory Pattern
CarFactory factory=new CarFactory();
Car i10=factory.getCar("i10");
i10.start();
i10.stop();
//Singleton Pattern
BillGates billGates=BillGates.getInstance();
billGates.getMessage();
//Abstract factory pattern
ApplianceFactory samsung=new Samsung();
Appliance dishwasher=samsung.getDishwasher();
dishwasher.switchOn();
//Builder pattern
PhoneBuilder builder=new PhoneBuilder();
builder.withMemory(8);
builder.withProcessor("Snapdragon 16");
builder.withStorage(256);
Phone phone=builder.build();
System.out.println(phone.toString());
//Prototype
TV firstInstance=new TV("Samsung",56);
TV secondCopy=firstInstance.clone();
System.out.println(secondCopy.toString());
//strategy pattern
CartService cartService=new CartService();
System.out.println(cartService.getTax("US"));
//command pattern
Room room=new Room();
room.switchOnAllLights();
room.switchOffAllLights();
//iterator pattern
EvenNumberCollection evenNumberCollection=new EvenNumberCollection(100);
evenNumberCollection.forEachRemaining(System.out::println);
//facade pattern
Cart cart=new Cart(Arrays.asList(new LineItem("12345",10.00,1)),10.00);
OrderFacade orderFacade=new OrderFacade();
Order order=orderFacade.placeOrder(cart);
System.out.println("Total $"+ order.getTotal());
//bridge pattern - abstraction and implementation
SedanCar sedanCar=new SedanCar(new Workshop1());
sedanCar.manufacture();
//composite pattern
OrderBox orderBox=new OrderBox(new ShoeBox(10),
new AirFryerBox(50),
new OrderBox(new ShoeBox(10),new AirFryerBox(50)));
System.out.println(orderBox.getWeight());
}
}
// Factory Pattern
interface Car
{
void start();
void stop();
}
class I10 implements Car{
@Override
public void start() {
System.out.println("i10 starts");
}
@Override
public void stop() {
System.out.println("i10 stops");
}
}
class I20 implements Car{
@Override
public void start() {
System.out.println("i20 starts");
}
@Override
public void stop() {
System.out.println("i20 stops");
}
}
class CarFactory
{
Car getCar(String model){
return switch (model)
{
case "i10"->new I10();
case "i20"->new I20();
default -> throw new UnsupportedOperationException();
};
}
}
// singleton
class BillGates{
private BillGates(){}
private static BillGates instance;
static BillGates getInstance()
{
if (instance == null) {
instance = new BillGates();
}
return instance;
}
void getMessage()
{
System.out.println("There is only one "+getClass().getName()+" in this world");
}
}
// abstract factory pattern
interface Appliance
{
void switchOn();
void switchOff();
}
interface ApplianceFactory
{
Appliance getHairDryer();
Appliance getDishwasher();
}
class LGHairDryer implements Appliance
{
@Override
public void switchOn() {
System.out.println("On");
}
@Override
public void switchOff() {
System.out.println("Off");
}
}
class LGDishWasher implements Appliance
{
@Override
public void switchOn() {
System.out.println("On");
}
@Override
public void switchOff() {
System.out.println("Off");
}
}
class SamsungHairDryer implements Appliance
{
@Override
public void switchOn() {
System.out.println("On");
}
@Override
public void switchOff() {
System.out.println("Off");
}
}
class SamsungDishWasher implements Appliance
{
@Override
public void switchOn() {
System.out.println("On");
}
@Override
public void switchOff() {
System.out.println("Off");
}
}
class LG implements ApplianceFactory
{
@Override
public Appliance getHairDryer() {
return new LGHairDryer();
}
@Override
public Appliance getDishwasher() {
return new LGDishWasher();
}
}
class Samsung implements ApplianceFactory
{
@Override
public Appliance getHairDryer() {
return new SamsungHairDryer();
}
@Override
public Appliance getDishwasher() {
return new SamsungDishWasher();
}
}
// builder pattern
class Phone
{
private String processor;
private Integer memory;
private Integer storage;
public Phone(String processor, Integer memory, Integer storage) {
this.processor = processor;
this.memory = memory;
this.storage = storage;
}
@Override
public String toString() {
return String.format("Phone with %s processor with %d GB memory and %d GB storage",processor,memory,storage);
}
}
class PhoneBuilder
{
private String processor;
private Integer memory;
private Integer storage;
public void withProcessor(String processor)
{
this.processor=processor;
}
public void withMemory(Integer memory)
{
this.memory=memory;
}
public void withStorage(Integer storage)
{
this.storage=storage;
}
public Phone build()
{
return new Phone(processor,memory,storage);
}
}
//prototype pattern
class TV implements Cloneable
{
private String name;
private Integer screenSize;
TV(String name,Integer screenSize)
{
this.screenSize=screenSize;
this.name=name;
}
TV(TV tv)
{
this.name=tv.name;
this.screenSize=tv.screenSize;
}
@Override
public TV clone() {
return new TV(this);
}
@Override
public String toString() {
return String.format("%s TV with %d inch screen size",name,screenSize);
}
}
//Strategy Pattern
interface TaxCalculationStrategy
{
Double calculateTax();
}
class USTaxCalulationStrategy implements TaxCalculationStrategy
{
@Override
public Double calculateTax() {
return 10.0;
}
}
class CanadaTaxCalulationStrategy implements TaxCalculationStrategy
{
@Override
public Double calculateTax() {
return 5.0;
}
}
class CartService{
private Map<String,TaxCalculationStrategy> taxStrategies=new HashMap<String,TaxCalculationStrategy>();
CartService()
{
taxStrategies.put("US",new USTaxCalulationStrategy());
taxStrategies.put("CA",new CanadaTaxCalulationStrategy());
}
public Double getTax(String country)
{
return taxStrategies.get(country).calculateTax();
}
}
//command pattern
interface Command
{
void execute();
}
class Light
{
void switchOff()
{
System.out.println("Light Off");
}
void switchOn()
{
System.out.println("Light on");
}
}
class Room
{
Light light;
LightSwitchOnCommand lightSwitchOnCommand;
LightSwitchOffCommand lightSwitchOffCommand;
Room()
{
light=new Light();
lightSwitchOnCommand=new LightSwitchOnCommand(light);
lightSwitchOffCommand=new LightSwitchOffCommand(light);
}
public void switchOffAllLights()
{
lightSwitchOffCommand.execute();
}
public void switchOnAllLights()
{
lightSwitchOnCommand.execute();
}
}
class LightSwitchOnCommand implements Command
{
private Light light;
LightSwitchOnCommand(Light light)
{
this.light=light;
}
@Override
public void execute() {
this.light.switchOn();
}
}
class LightSwitchOffCommand implements Command
{
private Light light;
LightSwitchOffCommand(Light light)
{
this.light=light;
}
@Override
public void execute() {
this.light.switchOff();
}
}
// iterator pattern
class EvenNumberCollection implements Iterator<Integer>
{
private Integer limit;
private Integer start=0;
EvenNumberCollection(Integer limit)
{
this.limit=limit;
}
@Override
public boolean hasNext() {
return (start+2)<=limit;
}
@Override
public Integer next() {
int value=start;
start+=2;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void forEachRemaining(Consumer<? super Integer> action) {
while(hasNext())
{
action.accept(next());
}
}
}
//facade pattern
class InventoryService
{
void deductInventory(String sku, int qty)
{
System.out.println(String.format("%s qty deducted by %d",sku,qty));
}
}
class LineItem
{
private String sku;
private Double price;
private Integer qty;
public LineItem(String sku, Double price, Integer qty) {
this.sku = sku;
this.price = price;
this.qty = qty;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
}
abstract class AbstractOrder
{
private List<LineItem> lineItemList;
private Double total;
public List<LineItem> getLineItemList() {
return lineItemList;
}
public void setLineItemList(List<LineItem> lineItemList) {
this.lineItemList = lineItemList;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
}
class Cart extends AbstractOrder
{
public Cart(List<LineItem> lines,Double total) {
super.setLineItemList(lines);
super.setTotal(total);
}
}
class Order extends AbstractOrder
{
private String status;
public Order(List<LineItem> lines,Double total,String status) {
super.setLineItemList(lines);
super.setTotal(total);
this.status=status;
}
}
class OrderService
{
Order createOrder(Cart cart)
{
Order order=new Order(cart.getLineItemList(),cart.getTotal(),"CREATED");
return order;
}
}
class OrderFacade
{
private OrderService orderService=new OrderService();
private InventoryService inventoryService=new InventoryService();
Order placeOrder(Cart cart) {
Order order=orderService.createOrder(cart);
order.getLineItemList().forEach(li->{
inventoryService.deductInventory(li.getSku(),li.getQty());
});
return order;
}
}
// bridge pattern
abstract class Vehicle
{
protected Workshop workshop;
protected Vehicle(Workshop workshop) {
this.workshop=workshop;
}
abstract void manufacture();
}
abstract class Workshop
{
abstract void work();
}
class SedanCar extends Vehicle
{
public SedanCar(Workshop workshop) {
super(workshop);
}
@Override
void manufacture() {
workshop.work();
}
}
class Workshop1 extends Workshop
{
@Override
void work() {
System.out.println("manufactured!!!");
}
}
//composite pattern
interface Box
{
double getWeight();
}
class ShoeBox implements Box{
private double weight;
public ShoeBox(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return this.weight;
}
}
class AirFryerBox implements Box{
private double weight;
public AirFryerBox(double weight) {
this.weight = weight;
}
@Override
public double getWeight() {
return this.weight;
}
}
class OrderBox implements Box
{
private List<Box> boxes;
public OrderBox(Box... boxes) {
this.boxes = Arrays.asList(boxes);
}
@Override
public double getWeight() {
return this.boxes.stream().map(b->b.getWeight()).reduce((value,sum)->sum+=value).get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment