Java Reference
In-Depth Information
default: throw new RuntimeException("No such product " + name);
}
}
}
Here, Loan, Stock, and Bond are all subtypes of Product. The createProduct method could have
additional logic to configure each created product. But the benefit is that you can now create
these objects without exposing the constructor and the configuration to the client, which makes
the creation of products simpler for the client:
Product p = ProductFactory.createProduct("loan");
Using lambda expressions
You saw in chapter 3 that you can refer to constructors just like you refer to methods, by using
method references. For example, here's how to refer to the Loan constructor:
Supplier<Product> loanSupplier = Loan::new;
Loan loan = loanSupplier.get();
Using this technique, you could rewrite the previous code by creating a Map that maps a product
name to its constructor:
final static Map<String, Supplier<Product>> map = new HashMap<>();
static {
map.put("loan", Loan::new);
map.put("stock", Stock::new);
map.put("bond", Bond::new);
}
You can now use this Map to instantiate different products, just as you did with the factory
design pattern:
public static Product createProduct(String name){
Supplier<Product> p = map.get(name);
if(p != null) return p.get();
throw new IllegalArgumentException("No such product " + name);
}
 
Search WWH ::




Custom Search