Бидэнд нийт 3 класс, 1 интерфэйс хэрэгтэй болно.
Класс:
1. Тогооч класс - Chef class
2. Пизза класс - Pizza class
3. Хэрэглэгчийн хүлээн класс - UI class
2. Пизза класс - Pizza class
3. Хэрэглэгчийн хүлээн класс - UI class
Интерфэйс:
1. Тогоочын хүлээн авах интерфэйс - ChefListener interface
1. Pizza class
public class Pizza {
private String name;
private double price;
private double cookingTime; // in seconds
public Pizza(String name, double price, double cookingTime) {
this.name = name;
this.price = price;
this.cookingTime = cookingTime;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public double getCookingTime() {
return cookingTime;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public void setCookingTime(double cookingTime) {
this.cookingTime = cookingTime;
}
}
2. Chef class - Тредээс удамшина
public class Chef extends Thread{
Pizza pizza;
ChefListener listener;
public Chef(Pizza pizza, ChefListener listener) {
this.pizza = pizza;
this.listener = listener;
}
@Override
public void run() {
try {
Thread.sleep((long) (pizza.getCookingTime() * 1000));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
listener.pizzaCooked(pizza);
}
}
3. ChefListener interface
public interface ChefListener {
public void pizzaCooked( Pizza pizza );
}
4. UI class нь ChefListener -с удамшина
public class UI implements ChefListener {
public static void main(String[] args) {
UI ui = new UI();
for (int i = 0; i < 3; i++) {
ui.prompt();
}
}
public void prompt() {
Pizza ct = new Pizza("Cheese and Tomato", 2, 5);
Pizza bbq = new Pizza("BBQ", 5, 10);
Pizza vs = new Pizza("Vegetarian Supreme", 12, 8);
Pizza[] availablePizzas = new Pizza[]{ct, bbq, vs};
System.out.println("Please choose which pizza do you want: ");
for (Pizza p : availablePizzas) {
System.out.println(p.getName());
}
int choice = Integer.parseInt(JOptionPane.showInputDialog("Choose your pizza: "));
Pizza selection = availablePizzas[choice];
Chef chef = new Chef(selection, this);
chef.start();
}
@Override
public void pizzaCooked(Pizza pizza) {
System.out.println(pizza.getName() + " pizza has been cooked. Enjoy!");
}
}
No comments:
Post a Comment