Created
March 2, 2017 05:34
-
-
Save leogtzr/25774f3d05a1f6eea965ea382faf7731 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum ShapeType { | |
CIRCLE { | |
@Override | |
public Supplier<Shape> create() { | |
return Circle::new; | |
} | |
}, | |
RECTANGLE { | |
@Override | |
public Supplier<Shape> create() { | |
return Rectangle::new; | |
} | |
} | |
; | |
abstract Supplier<Shape> create(); | |
} | |
final class Factory { | |
private Factory() {} | |
public static Shape getShape(final ShapeType type) { | |
return type.create().get(); | |
} | |
} |
Hi @pgioseffi, what I tried to do here in this Gist is to show how to create Shapes using the classic factory method pattern (the one where you pass the type as an argument and get an instance of that type), but I agree with you, this is also possible:
final Shape circle = ShapeType.CIRCLE.create().get();
final Shape rectangle = ShapeType.RECTANGLE.create().get();
This is the full example:
public class App {
public static void main(final String ... args) {
final Shape circle = ShapeType.CIRCLE.create().get();
final Shape rectangle = ShapeType.RECTANGLE.create().get();
circle.draw();
rectangle.draw();
}
}
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle ... ");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle ... ");
}
}
enum ShapeType {
CIRCLE {
@Override
public Supplier<Shape> create() {
return Circle::new;
}
},
RECTANGLE {
@Override
public Supplier<Shape> create() {
return Rectangle::new;
}
}
;
abstract Supplier<Shape> create();
}
final class Factory {
private Factory() {}
public static Shape getShape(final ShapeType type) {
return type.create().get();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not make the enum public and use its entry directly to instance Shapes preventing the creation of the Factory class?