// patterns/ShapeFactory3.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// Polymorphic factory methodsimport java.util.*;import java.util.function.*;import java.util.stream.*;import patterns.shapes.*;interface PolymorphicFactory {Shape create();}class RandomShapes implements Supplier<Shape> {private final PolymorphicFactory[] factories;private Random rand = new Random(42);RandomShapes(PolymorphicFactory... factories) {this.factories = factories;}public Shape get() {return factories[rand.nextInt(factories.length)].create();}}public class ShapeFactory3 {public static void main(String[] args) {RandomShapes rs = new RandomShapes(Circle::new, Square::new, Triangle::new);Stream.generate(rs).limit(6).peek(Shape::draw).peek(Shape::erase).count();}}/* Output:Triangle[0] drawTriangle[0] eraseCircle[1] drawCircle[1] eraseCircle[2] drawCircle[2] eraseTriangle[3] drawTriangle[3] eraseCircle[4] drawCircle[4] eraseSquare[5] drawSquare[5] erase*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。