Singleton
public class Singleton {
// Step 1: Private static instance of the class (this will be the only
instance)
private static Singleton instance;
// Step 2: Private constructor to prevent instantiation from outside the
class
private Singleton() {
// Private constructor to prevent instantiation
}
// Step 3: Public method to provide access to the instance
public static Singleton getInstance() {
// If the instance is null, create a new one
if (instance == null) {
instance = new Singleton();
}
// Return the single instance
return instance;
}
// Example method to demonstrate the singleton functionality
public void showMessage() {
[Link]("Hello from the Singleton class!");
}
public static void main(String[] args) {
// Step 4: Get the unique instance of the Singleton class
Singleton singleton = [Link]();
// Call a method on the Singleton instance
[Link]();
}
}
Factory Method
// Step 1: Create an abstract class or interface for the product (Shape)
abstract class Shape {
public abstract void draw();
}
// Step 2: Concrete classes implementing the Shape interface
class Circle extends Shape {
@Override
public void draw() {
[Link]("Drawing a Circle");
}
}
class Rectangle extends Shape {
@Override
public void draw() {
[Link]("Drawing a Rectangle");
}
}
class Square extends Shape {
@Override
public void draw() {
[Link]("Drawing a Square");
}
}
// Step 3: Create an abstract creator class (ShapeFactory) that declares the
factory method
abstract class ShapeFactory {
public abstract Shape createShape();
public void drawShape() {
Shape shape = createShape();
[Link]();
}
}
// Step 4: Concrete creators that implement the factory method
class CircleFactory extends ShapeFactory {
@Override
public Shape createShape() {
return new Circle(); // Factory method returns a Circle object
}
}
class RectangleFactory extends ShapeFactory {
@Override
public Shape createShape() {
return new Rectangle(); // Factory method returns a Rectangle object
}
}
class SquareFactory extends ShapeFactory {
@Override
public Shape createShape() {
return new Square(); // Factory method returns a Square object
}
}
// Step 5: Client class to test the Factory Method Design Pattern
public class FactoryMethodExample {
public static void main(String[] args) {
// Using different factories to create shapes
ShapeFactory circleFactory = new CircleFactory();
[Link]();
ShapeFactory rectangleFactory = new RectangleFactory();
[Link]();
ShapeFactory squareFactory = new SquareFactory();
[Link]();
}
}
Abstract Factory
// Step 1: Abstract Product Interfaces
interface Button {
void render();
}
interface Checkbox {
void render();
}
// Step 2: Concrete Product Classes
class WindowsButton implements Button {
@Override
public void render() {
[Link]("Rendering a Windows Button");
}
}
class WindowsCheckbox implements Checkbox {
@Override
public void render() {
[Link]("Rendering a Windows Checkbox");
}
}
class MacButton implements Button {
@Override
public void render() {
[Link]("Rendering a Mac Button");
}
}
class MacCheckbox implements Checkbox {
@Override
public void render() {
[Link]("Rendering a Mac Checkbox");
}
}
// Step 3: Abstract Factory Class
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
// Step 4: Concrete Factory Classes
class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton(); // Creates a Windows-specific button
}
@Override
public Checkbox createCheckbox() {
return new WindowsCheckbox(); // Creates a Windows-specific checkbox
}
}
class MacFactory implements GUIFactory {
@Override
public Button createButton() {
return new MacButton(); // Creates a Mac-specific button
}
@Override
public Checkbox createCheckbox() {
return new MacCheckbox(); // Creates a Mac-specific checkbox
}
}
// Step 5: Client Code
public class AbstractFactoryExample {
private Button button;
private Checkbox checkbox;
// Constructor to accept a GUIFactory and create products
public AbstractFactoryExample(GUIFactory factory) {
button = [Link]();
checkbox = [Link]();
}
// Render the products
public void renderUI() {
[Link]();
[Link]();
}
public static void main(String[] args) {
// Use WindowsFactory to create Windows-based UI elements
GUIFactory windowsFactory = new WindowsFactory();
AbstractFactoryExample windowsApp = new
AbstractFactoryExample(windowsFactory);
[Link]();
[Link]();
// Use MacFactory to create Mac-based UI elements
GUIFactory macFactory = new MacFactory();
AbstractFactoryExample macApp = new AbstractFactoryExample(macFactory);
[Link]();
}
}
Builder
// Step 1: Product Class
class Car {
private String engine;
private String wheels;
private String color;
private boolean sunroof;
// Constructor is private to ensure only the builder can create it
private Car(CarBuilder builder) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}
// Getters for the fields
public String getEngine() {
return engine;
}
public String getWheels() {
return wheels;
}
public String getColor() {
return color;
}
public boolean hasSunroof() {
return sunroof;
}
// Step 2: Builder Class
public static class CarBuilder {
private String engine;
private String wheels;
private String color;
private boolean sunroof;
// Set the engine type (mandatory)
public CarBuilder setEngine(String engine) {
[Link] = engine;
return this;
}
// Set the wheels type (mandatory)
public CarBuilder setWheels(String wheels) {
[Link] = wheels;
return this;
}
// Set the color (optional)
public CarBuilder setColor(String color) {
[Link] = color;
return this;
}
// Set sunroof option (optional)
public CarBuilder setSunroof(boolean sunroof) {
[Link] = sunroof;
return this;
}
// Step 3: Build the Car object
public Car build() {
return new Car(this);
}
}
}
// Step 4: Client Code
public class BuilderPatternExample {
public static void main(String[] args) {
// Creating a car using the builder pattern
Car car = new [Link]()
.setEngine("V8")
.setWheels("Alloy")
.setColor("Red")
.setSunroof(true)
.build();
// Printing the details of the created car
[Link]("Car Engine: " + [Link]());
[Link]("Car Wheels: " + [Link]());
[Link]("Car Color: " + [Link]());
[Link]("Has Sunroof: " + [Link]());
}
}
Prototype
// Step 1: Prototype Interface
interface Prototype {
Prototype clone();
}
// Step 2: Concrete Prototype Class
class Car implements Prototype {
private String model;
private String color;
private int year;
// Constructor
public Car(String model, String color, int year) {
[Link] = model;
[Link] = color;
[Link] = year;
}
// Getter methods
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public int getYear() {
return year;
}
// Step 3: Clone method implementation
@Override
public Prototype clone() {
return new Car([Link], [Link], [Link]); // Creating a copy
with the same values
}
@Override
public String toString() {
return "Car [Model=" + model + ", Color=" + color + ", Year=" + year +
"]";
}
}
// Step 4: Client Code
public class PrototypePatternExample {
public static void main(String[] args) {
// Creating the original object
Car originalCar = new Car("Tesla Model S", "Red", 2022);
[Link]("Original Car: " + originalCar);
// Cloning the original car
Car clonedCar = (Car) [Link]();
[Link]("Cloned Car: " + clonedCar);
// Modifying the cloned object
clonedCar = new Car("Tesla Model X", "Black", 2023); // Simulating a
change in cloned object
[Link]("Modified Cloned Car: " + clonedCar);
}
}
Decorator
// Step 1: Component Interface
interface Coffee {
double cost();
String ingredients();
}
// Step 2: Concrete Component
class SimpleCoffee implements Coffee {
@Override
public double cost() {
return 5.0; // Base cost of simple coffee
}
@Override
public String ingredients() {
return "Coffee"; // Base ingredients
}
}
// Step 3: Decorator Class
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee; // This is the wrapped Coffee object
public CoffeeDecorator(Coffee coffee) {
[Link] = coffee;
}
@Override
public double cost() {
return [Link](); // Default cost behavior, can be modified
by concrete decorators
}
@Override
public String ingredients() {
return [Link](); // Default ingredients behavior,
can be modified by concrete decorators
}
}
// Step 4: Concrete Decorators
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return [Link]() + 1.5; // Add milk cost
}
@Override
public String ingredients() {
return [Link]() + ", Milk"; // Add milk to
ingredients
}
}
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return [Link]() + 0.5; // Add sugar cost
}
@Override
public String ingredients() {
return [Link]() + ", Sugar"; // Add sugar to
ingredients
}
}
// Step 5: Client Code
public class DecoratorPatternExample {
public static void main(String[] args) {
// Create a basic coffee
Coffee simpleCoffee = new SimpleCoffee();
[Link]("Cost: " + [Link]());
[Link]("Ingredients: " + [Link]());
// Decorate the coffee with milk
Coffee milkCoffee = new MilkDecorator(simpleCoffee);
[Link]("\nCost with Milk: " + [Link]());
[Link]("Ingredients with Milk: " + [Link]());
// Decorate the coffee with milk and sugar
Coffee milkSugarCoffee = new SugarDecorator(milkCoffee);
[Link]("\nCost with Milk and Sugar: " +
[Link]());
[Link]("Ingredients with Milk and Sugar: " +
[Link]());
}
}
Adapter
// Step 1: Target Interface
interface MediaPlayer {
void play(String audioType, String fileName);
}
// Step 2: Adaptee Class
class MediaAdapter implements MediaPlayer {
private AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType) {
if([Link]("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if([Link]("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
@Override
public void play(String audioType, String fileName) {
if([Link]("vlc")){
[Link](fileName);
} else if([Link]("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
// Step 3: Adaptee Interface
interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
// Step 4: Concrete Adaptee Classes
class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
[Link]("Playing vlc file. Name: " + fileName);
}
@Override
public void playMp4(String fileName) {
// Do nothing, as VlcPlayer doesn't support mp4
}
}
class Mp4Player implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
// Do nothing, as Mp4Player doesn't support vlc
}
@Override
public void playMp4(String fileName) {
[Link]("Playing mp4 file. Name: " + fileName);
}
}
// Step 5: Client Code
public class AdapterPatternExample {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
// Playing mp3 file (already supported by AudioPlayer)
[Link]("mp3", "beyond the horizon.mp3");
// Playing vlc file using Adapter
[Link]("vlc", "far far [Link]");
// Playing mp4 file using Adapter
[Link]("mp4", "alone.mp4");
}
}
// Step 6: Client Class using Adapter
class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String fileName) {
// If the audio type is mp3, we can play it directly
if([Link]("mp3")){
[Link]("Playing mp3 file. Name: " + fileName);
}
// If it's a different audio type, we use the MediaAdapter
else if([Link]("vlc") ||
[Link]("mp4")){
mediaAdapter = new MediaAdapter(audioType);
[Link](audioType, fileName);
}
else {
[Link]("Invalid media. " + audioType + " format not
supported.");
}
}
}
Proxy
// Step 1: Subject Interface
interface Image {
void display();
}
// Step 2: RealSubject Class
class RealImage implements Image {
private String fileName;
public RealImage(String fileName) {
[Link] = fileName;
loadFromDisk();
}
private void loadFromDisk() {
[Link]("Loading image: " + fileName);
}
@Override
public void display() {
[Link]("Displaying image: " + fileName);
}
}
// Step 3: Proxy Class
class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName) {
[Link] = fileName;
}
@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName); // Lazy initialization
}
[Link]();
}
}
// Step 4: Client Code
public class ProxyPatternExample {
public static void main(String[] args) {
// Using Proxy to access RealImage object
Image image1 = new ProxyImage("[Link]");
Image image2 = new ProxyImage("[Link]");
// Image will be loaded only when it is displayed (Lazy Initialization)
[Link](); // RealImage is loaded and displayed
[Link](); // RealImage is not loaded again
[Link](); // RealImage is loaded and displayed
}
}
Bridge
// Step 1: Implementer Interface
interface Device {
void turnOn();
void turnOff();
void setVolume(int volume);
}
// Step 2: ConcreteImplementer Classes
class TV implements Device {
private int volume;
@Override
public void turnOn() {
[Link]("Turning on the TV.");
}
@Override
public void turnOff() {
[Link]("Turning off the TV.");
}
@Override
public void setVolume(int volume) {
[Link] = volume;
[Link]("Setting TV volume to " + volume);
}
}
class Radio implements Device {
private int volume;
@Override
public void turnOn() {
[Link]("Turning on the Radio.");
}
@Override
public void turnOff() {
[Link]("Turning off the Radio.");
}
@Override
public void setVolume(int volume) {
[Link] = volume;
[Link]("Setting Radio volume to " + volume);
}
}
// Step 3: Abstraction Class
abstract class RemoteControl {
protected Device device;
public RemoteControl(Device device) {
[Link] = device;
}
public abstract void turnOn();
public abstract void turnOff();
public abstract void setVolume(int volume);
}
// Step 4: RefinedAbstraction Class
class BasicRemoteControl extends RemoteControl {
public BasicRemoteControl(Device device) {
super(device);
}
@Override
public void turnOn() {
[Link]();
}
@Override
public void turnOff() {
[Link]();
}
@Override
public void setVolume(int volume) {
[Link](volume);
}
}
class AdvancedRemoteControl extends RemoteControl {
public AdvancedRemoteControl(Device device) {
super(device);
}
@Override
public void turnOn() {
[Link]();
}
@Override
public void turnOff() {
[Link]();
}
@Override
public void setVolume(int volume) {
[Link](volume);
}
public void mute() {
[Link]("Muting the device.");
}
}
// Step 5: Client Code
public class BridgePatternExample {
public static void main(String[] args) {
// Using TV with BasicRemoteControl
Device tv = new TV();
RemoteControl basicRemote = new BasicRemoteControl(tv);
[Link]();
[Link](10);
[Link]();
// Using Radio with AdvancedRemoteControl
Device radio = new Radio();
RemoteControl advancedRemote = new AdvancedRemoteControl(radio);
[Link]();
[Link](5);
((AdvancedRemoteControl) advancedRemote).mute(); // Advanced feature
[Link]();
}
}
Iterator
// Step 1: Iterator Interface
interface Iterator {
boolean hasNext();
Object next();
}
// Step 2: ConcreteIterator Class
class NameIterator implements Iterator {
private String[] names;
private int position;
public NameIterator(String[] names) {
[Link] = names;
[Link] = 0;
}
@Override
public boolean hasNext() {
return position < [Link];
}
@Override
public Object next() {
if (hasNext()) {
return names[position++];
}
return null;
}
}
// Step 3: Aggregate Interface
interface Aggregate {
Iterator createIterator();
}
// Step 4: ConcreteAggregate Class
class NameRepository implements Aggregate {
private String[] names;
public NameRepository(String[] names) {
[Link] = names;
}
@Override
public Iterator createIterator() {
return new NameIterator(names);
}
}
// Step 5: Client Code
public class IteratorPatternExample {
public static void main(String[] args) {
String[] names = {"John", "Jane", "Alice", "Bob"};
NameRepository nameRepository = new NameRepository(names);
Iterator iterator = [Link]();
[Link]("Iterating over names:");
while ([Link]()) {
[Link]([Link]());
}
}
}
Memento
// Step 1: Memento Class
class Memento {
private String state;
public Memento(String state) {
[Link] = state;
}
public String getState() {
return state;
}
}
// Step 2: Originator Class
class Originator {
private String state;
public void setState(String state) {
[Link] = state;
[Link]("State set to: " + state);
}
public String getState() {
return state;
}
// Creates a Memento to save the current state
public Memento saveStateToMemento() {
return new Memento(state);
}
// Restores the state from a Memento
public void restoreStateFromMemento(Memento memento) {
state = [Link]();
[Link]("State restored to: " + state);
}
}
// Step 3: Caretaker Class
class Caretaker {
private Memento memento;
public void saveState(Originator originator) {
memento = [Link]();
}
public void restoreState(Originator originator) {
[Link](memento);
}
}
// Step 4: Client Code
public class MementoPatternExample {
public static void main(String[] args) {
Originator originator = new Originator();
Caretaker caretaker = new Caretaker();
// Set and save state
[Link]("State1");
[Link](originator);
// Change state
[Link]("State2");
// Restore the state to the previous state
[Link](originator);
}
}
State
// Step 1: State Interface
interface State {
void doAction(Context context);
}
// Step 2: ConcreteStateA Class
class ConcreteStateA implements State {
@Override
public void doAction(Context context) {
[Link]("State A: Performing action...");
[Link](new ConcreteStateB()); // Transition to State B
}
}
// Step 3: ConcreteStateB Class
class ConcreteStateB implements State {
@Override
public void doAction(Context context) {
[Link]("State B: Performing action...");
[Link](new ConcreteStateA()); // Transition to State A
}
}
// Step 4: Context Class
class Context {
private State state;
public Context() {
[Link] = new ConcreteStateA(); // Initial state
}
public void setState(State state) {
[Link] = state;
}
public State getState() {
return state;
}
public void request() {
[Link](this); // Delegates action to current state
}
}
// Step 5: Client Code
public class StatePatternExample {
public static void main(String[] args) {
Context context = new Context();
// Perform actions based on the state
[Link](); // In State A
[Link](); // In State B
[Link](); // In State A again
}
}
Delegator
// Step 1: Delegator Interface
interface Printer {
void printDocument(String document);
}
// Step 2: ConcreteDelegate Class (Performs the work)
class PrinterImpl implements Printer {
@Override
public void printDocument(String document) {
[Link]("Printing document: " + document);
}
}
// Step 3: ConcreteDelegator Class (Delegates the task)
class DelegatorPrinter implements Printer {
private Printer printer;
public DelegatorPrinter() {
// Here, we're delegating the printing task to PrinterImpl
[Link] = new PrinterImpl();
}
@Override
public void printDocument(String document) {
[Link]("DelegatorPrinter: Delegating the print task to
PrinterImpl.");
[Link](document); // Delegating the actual task to
PrinterImpl
}
}
// Step 4: Client Code
public class DelegatorPatternExample {
public static void main(String[] args) {
// Create a Delegator object
Printer printer = new DelegatorPrinter();
// Request to print a document
[Link]("Design Patterns in Java");
}
}
Visitor
// Step 1: Visitor Interface
interface Visitor {
void visit(ConcreteElementA element);
void visit(ConcreteElementB element);
}
// Step 2: Concrete Visitor (Performs actions based on element types)
class ConcreteVisitor implements Visitor {
@Override
public void visit(ConcreteElementA element) {
[Link]("Visiting ConcreteElementA");
[Link]();
}
@Override
public void visit(ConcreteElementB element) {
[Link]("Visiting ConcreteElementB");
[Link]();
}
}
// Step 3: Element Interface
interface Element {
void accept(Visitor visitor);
}
// Step 4: Concrete ElementA
class ConcreteElementA implements Element {
@Override
public void accept(Visitor visitor) {
[Link](this); // Accept the visitor
}
public void doSomethingA() {
[Link]("Element A: Doing something A");
}
}
// Step 5: Concrete ElementB
class ConcreteElementB implements Element {
@Override
public void accept(Visitor visitor) {
[Link](this); // Accept the visitor
}
public void doSomethingB() {
[Link]("Element B: Doing something B");
}
}
// Step 6: Client Code
public class VisitorPatternExample {
public static void main(String[] args) {
// Create elements
Element elementA = new ConcreteElementA();
Element elementB = new ConcreteElementB();
// Create a visitor
Visitor visitor = new ConcreteVisitor();
// Accept the visitor
[Link](visitor); // Visitor visits Element A
[Link](visitor); // Visitor visits Element B
}
}
Observer
// Step 1: Observer Interface
interface Observer {
void update(float temperature);
}
// Step 2: Subject Interface
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// Step 3: ConcreteSubject (WeatherStation)
class WeatherStation implements Subject {
private float temperature;
private List<Observer> observers;
public WeatherStation() {
observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer observer) {
[Link](observer);
}
@Override
public void removeObserver(Observer observer) {
[Link](observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
[Link](temperature);
}
}
public void setTemperature(float temperature) {
[Link] = temperature;
notifyObservers(); // Notify all observers about the temperature change
}
}
// Step 4: ConcreteObserver (TemperatureDisplay)
class TemperatureDisplay implements Observer {
private String displayName;
public TemperatureDisplay(String displayName) {
[Link] = displayName;
}
@Override
public void update(float temperature) {
[Link](displayName + " Display: Temperature updated to " +
temperature + "°C");
}
}
// Step 5: Client Code
public class ObserverPatternExample {
public static void main(String[] args) {
// Create the weather station (subject)
WeatherStation weatherStation = new WeatherStation();
// Create display devices (observers)
Observer display1 = new TemperatureDisplay("Living Room");
Observer display2 = new TemperatureDisplay("Bedroom");
// Register observers
[Link](display1);
[Link](display2);
// Simulate temperature change
[Link](25.5f); // This will notify both displays
// Remove a display and change the temperature again
[Link](display1);
[Link](30.0f); // Only Bedroom display will be
notified
}
}
First UML
public class Andalusian extends Horse {
public Andalusian(String id, int raceDistance, int index) {
super(id, raceDistance, index);
}
}
public class Appaloosa extends Horse {
public Appaloosa(String id, int raceDistance, int index) {
super(id, raceDistance, index);
}
}
public class Friesian extends Horse {
public Friesian(String id, int raceDistance, int index) {
super(id, raceDistance, index);
}
}
public class HorseFactory {
public static Horse createHorse(String type, String id, int raceDistance, int
index) {
switch ([Link]()) {
case "andalusian":
return new Andalusian(id, raceDistance, index);
case "appaloosa":
return new Appaloosa(id, raceDistance, index);
case "friesian":
return new Friesian(id, raceDistance, index);
default:
throw new IllegalArgumentException(type + " is unknown horse type.");
}
}
}
import [Link];
public abstract class Horse implements Runnable {
private static Random random = new Random();
private String id;
private int raceDistance;
private int index;
private int coveredDistance;
public Horse(String id, int raceDistance, int index) {
[Link] = id;
[Link] = raceDistance;
[Link] = index;
[Link] = 0;
}
public String getId() {
return [Link];
}
public int getIndex() {
return [Link];
}
public int getCoveredDistance() {
return [Link];
}
public boolean hasFinished() {
return [Link] >= [Link];
}
private void moveForward() {
[Link] += [Link](10) + 1;
}
public void run() {
while (![Link]()) {
[Link]();
try {
[Link](200);
} catch (InterruptedException exception) {
// InterruptedException exception handling
}
}
}
}
import [Link];
import [Link];
public class Race {
private static Random random = new Random();
private static final int raceDistance = 100;
private static Race instance;
private ArrayList<Horse> horses;
private boolean raceInProgress;
private Race() {
[Link] = new ArrayList<>();
[Link] = true;
}
public static Race getInstance() {
if (instance == null) {
instance = new Race();
}
return instance;
}
public void initializeHorses() {
for (int i = 0; i < 10; i++) {
switch ([Link](3) + 1) {
case 1:
[Link]([Link]("andalusian", "H" + i,
raceDistance, i));
break;
case 2:
[Link]([Link]("appaloosa", "H" + i,
raceDistance, i));
break;
case 3:
[Link]([Link]("friesian", "H" + i,
raceDistance, i));
break;
}
}
}
public void displayHorses() {
[Link]("===== HORSES =====\n");
for (int i = 0; i < [Link](); i++) {
[Link]((i + 1) + ") " + [Link](i).getId() + " (" +
[Link](i).getClass().getSimpleName() + ")");
}
[Link]();
}
public void startRace() {
ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < [Link](); i++) {
Thread thread = new Thread([Link](i));
[Link](thread);
[Link]();
}
while ([Link]) {
try {
[Link](500);
} catch (InterruptedException exception) {
// InterruptedException exception handling
}
displayTopThreeHorses();
for (int i = 0; i < [Link](); i++) {
if ([Link](i).hasFinished()) {
[Link] = false;
[Link]("=====> RACE WINNER: " +
[Link](i).getId() + " (" +
[Link](i).getClass().getSimpleName() + ")");
break;
}
}
}
for (int i = 0; i < [Link](); i++) {
[Link](i).interrupt();
}
}
private void displayTopThreeHorses() {
for (int i = 0; i < [Link]() - 1; i++) {
for (int j = 0; j < [Link]() - i - 1; j++) {
if ([Link](j).getCoveredDistance() < [Link](j +
1).getCoveredDistance()) {
Horse temp = [Link](j);
[Link](j, [Link](j + 1));
[Link](j + 1, temp);
}
}
}
for (int i = 0; i < 3; i++) {
Horse horse = [Link](i);
int remainingDistance = [Link](0, raceDistance -
[Link](i).getCoveredDistance());
[Link](
"Horse Index: " + [Link]() + ".\n" +
"Horse Type: " + [Link]().getSimpleName() + ".\n" +
"Remaining Distance: " + remainingDistance + ".\n"
);
}
}
}
public class Demo {
public static void main(String[] args) {
Race race = [Link]();
[Link]();
[Link]();
[Link]();
}
}
Second UML
public interface Item {
public String name();
public double price();
}
public class Coke implements Item {
public String name() {
return "Coke";
}
public double price() {
return 2.5;
}
}
public class Pepsi implements Item {
public String name() {
return "Pepsi";
}
public double price() {
return 2.5;
}
}
public class ChickenBurger implements Item {
public String name() {
return "Chicken Burger";
}
public double price() {
return 10.0;
}
}
public class VegBurger implements Item {
public String name() {
return "Veg Burger";
}
public double price() {
return 5.0;
}
}
import [Link];
public class CostBridge {
public double getCost(ArrayList<Item> items) {
double cost = 0.0;
for (Item item : items) {
cost += [Link]();
}
return cost;
}
}
import [Link];
public class Meal {
private ArrayList<Item> items = new ArrayList<>();
private CostBridge costBridge = new CostBridge();
public void addItem(Item item) {
[Link](item);
}
public double getCost() {
return [Link]([Link]);
}
public void showItems() {
for (Item item : [Link]) {
[Link]("Item Name: %s, Item Price: %f\n", [Link](),
[Link]());
}
}
}
public class MealBuilder {
public Meal prepareVegMeal() {
Meal meal = new Meal();
[Link](new VegBurger());
[Link](new Coke());
return meal;
}
public Meal prepareNonVegMeal() {
Meal meal = new Meal();
[Link](new ChickenBurger());
[Link](new Pepsi());
return meal;
}
}
public class ProxyMealBuilder {
private MealBuilder mealBuilder = new MealBuilder();
public Meal prepareVegMeal() {
[Link]("ProxyMealBuilder: Preparing Veg Meal...");
return [Link]();
}
public Meal prepareNonVegMeal() {
[Link]("ProxyMealBuilder: Preparing Non Veg Meal...");
return [Link]();
}
}
public class BuilderPatternDemo {
public static void main(String[] args) {
ProxyMealBuilder proxyMealBuilder = new ProxyMealBuilder();
[Link]("Veg Meal:");
Meal vegMeal = [Link]();
[Link]();
[Link]("Total Cost: %f\n\n", [Link]());
[Link]("Non Veg Meal:");
Meal nonVegMeal = [Link]();
[Link]();
[Link]("Total Cost: %f\n", [Link]());
}
}
Third UML
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
public class BinaryObserver extends Observer {
public BinaryObserver(Subject subject) {
[Link] = subject;
[Link](this);
}
public void update() {
[Link]("Binary Observer: " +
[Link]([Link]()));
}
}
public class OctalObserver extends Observer {
public OctalObserver(Subject subject) {
[Link] = subject;
[Link](this);
}
public void update() {
[Link]("Octal Observer: " +
[Link]([Link]()));
}
}
public class HexaObserver extends Observer {
public HexaObserver(Subject subject) {
[Link] = subject;
[Link](this);
}
public void update() {
[Link]("Hexa Observer: " +
[Link]([Link]()));
}
}
import [Link];
public class Subject {
private ArrayList<Observer> observers = new ArrayList<>();
private int state;
public int getState() {
return [Link];
}
public void setState(int state) {
[Link] = state;
[Link]();
}
public void attach(Observer observer) {
[Link](observer);
}
public void notifyAllObservers() {
for (Observer observer : [Link]) {
[Link]();
}
}
}
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new BinaryObserver(subject);
new OctalObserver(subject);
new HexaObserver(subject);
[Link](2023);
[Link]();
[Link](2024);
[Link]();
[Link](2025);
}
}