Java Reference
In-Depth Information
Product anotherBook = bookType.createProduct("My second book", 244.99);
anotherBook.setProperty("title", anotherBook.getName());
anotherBook.setProperty("author", "Patternicus");
anotherBook.setProperty("pages", 800);
showBook(aBook);
showBook(anotherBook);
}
public static void showBook(Product bookProduct) {
System.out.format("Book '%s' from '%s' (%s pages) costs '%s' " +
"--> after discount = %s%n",
bookProduct.getProperty("title"),
bookProduct.getProperty("author"),
bookProduct.getProperty("pages"),
bookProduct.getPrice(),
((BookDiscountCalculator) bookProduct
.getStaticProperty("discountCalculator"))
.getDiscountedPrice(bookProduct.getPrice())
);
}
public static interface DiscountCalculator {
public double getDiscountedPrice(double originalPrice);
}
public static class BookDiscountCalculator implements DiscountCalculator {
@Override
public double getDiscountedPrice(double originalPrice) {
return Math.max(10, originalPrice * 0.60 - 10);
}
}
}
Note how it is now possible to define a discount calculator for each product type.
NOTe If you've been following along closely throughout this topic, you might
remember that Java defines the concept of a class as an actual class, as java.
lang.Class . Couldn't you just use that to make your classes at runtime,
programmatically? Sadly, no. The constructor for this class class is not visible.
The following will not work:
Class myClass = new Class();
If you want to get clever, you can use Java's reflection capabilities together
with a custom class loader to construct classes on the fly. If you want to see
this approach in action, the most basic proof of concept looks like this:
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
continues
Search WWH ::




Custom Search