English  

كتب لغة البرمجة جافا Java (18,990 كتاب)

اذا لم تجد ما تبحث عنه يمكنك استخدام كلمات أكثر دقة.

عرض المزيد

جافا Java (معلومة)

مثال بلغة برمجة جافا Java

import java.util.ArrayList;interface BillingStrategy {// Use a price in cents to avoid floating point round-off errorint getActPrice(int rawPrice);// Normal billing strategy (unchanged price)static BillingStrategy normalStrategy() {return rawPrice -> rawPrice;}// Strategy for Happy hour (50% discount)static BillingStrategy happyHourStrategy() {return rawPrice -> rawPrice / 2;} }class Customer {private final List<Integer> drinks = new ArrayList<>();private BillingStrategy strategy;public Customer(BillingStrategy strategy) {this.strategy = strategy;}public void add(int price, int quantity) {this.drinks.add(this.strategy.getActPrice(price*quantity));}// Payment of billpublic void printBill() {int sum = this.drinks.stream().mapToInt(v -> v).sum();System.out.println("Total due: " + sum);this.drinks.clear();}// Set Strategypublic void setStrategy(BillingStrategy strategy) {this.strategy = strategy;} }public class StrategyPattern {public static void main(String[] arguments) {// Prepare strategiesBillingStrategy normalStrategy= BillingStrategy.normalStrategy();BillingStrategy happyHourStrategy = BillingStrategy.happyHourStrategy();Customer firstCustomer = new Customer(normalStrategy);// Normal billingfirstCustomer.add(100, 1);// Start Happy HourfirstCustomer.setStrategy(happyHourStrategy);firstCustomer.add(100, 2);// New CustomerCustomer secondCustomer = new Customer(happyHourStrategy);secondCustomer.add(80, 1);// The Customer paysfirstCustomer.printBill();// End Happy HoursecondCustomer.setStrategy(normalStrategy);secondCustomer.add(130, 2);secondCustomer.add(250, 1);secondCustomer.printBill();} }

المصدر: wikipedia.org
إغلاق الإعلان
تصفح بدون إعلانات
إغلاق الإعلان
تصفح بدون إعلانات