OnJava8-Examples/patterns/factory/ShapeFactory1.java

81 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// patterns/factory/ShapeFactory1.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// A simple static factory method
2016-07-28 12:48:23 -06:00
// {java patterns.factory.ShapeFactory1}
2015-06-15 17:47:35 -07:00
package patterns.factory;
import java.util.*;
2015-11-03 12:00:44 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
2015-11-03 12:00:44 -08:00
class BadShapeCreation extends RuntimeException {
2015-06-15 17:47:35 -07:00
BadShapeCreation(String msg) {
super(msg);
}
}
abstract class Shape {
public abstract void draw();
public abstract void erase();
static Shape factory(String type)
throws BadShapeCreation {
switch(type) {
case "Circle": return new Circle();
case "Square": return new Square();
default:
throw new BadShapeCreation(type);
}
}
}
class Circle extends Shape {
Circle() {} // Friendly constructor
@Override
2015-11-03 12:00:44 -08:00
public void draw() {
System.out.println("Circle.draw");
}
2015-06-15 17:47:35 -07:00
@Override
2015-11-03 12:00:44 -08:00
public void erase() {
System.out.println("Circle.erase");
}
2015-06-15 17:47:35 -07:00
}
class Square extends Shape {
Square() {} // Friendly constructor
@Override
2015-11-03 12:00:44 -08:00
public void draw() {
System.out.println("Square.draw");
}
2015-06-15 17:47:35 -07:00
@Override
2015-11-03 12:00:44 -08:00
public void erase() {
System.out.println("Square.erase");
}
2015-06-15 17:47:35 -07:00
}
public class ShapeFactory1 {
2016-01-25 18:05:55 -08:00
public static void main(String[] args) {
2015-11-03 12:00:44 -08:00
List<Shape> shapes = Stream.of(
"Circle", "Square",
"Square", "Circle",
"Circle", "Square")
.map(Shape::factory)
.collect(Collectors.toList());
2015-06-15 17:47:35 -07:00
shapes.forEach(Shape::draw);
shapes.forEach(Shape::erase);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Circle.draw
Square.draw
Square.draw
Circle.draw
Circle.draw
Square.draw
Circle.erase
Square.erase
Square.erase
Circle.erase
Circle.erase
Square.erase
2015-09-07 11:44:36 -06:00
*/