Skip to content

Instantly share code, notes, and snippets.

@leogtzr
Created March 2, 2017 05:34
Show Gist options
  • Save leogtzr/25774f3d05a1f6eea965ea382faf7731 to your computer and use it in GitHub Desktop.
Save leogtzr/25774f3d05a1f6eea965ea382faf7731 to your computer and use it in GitHub Desktop.
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();
}
}
@pgioseffi
Copy link

Why not make the enum public and use its entry directly to instance Shapes preventing the creation of the Factory class?

@leogtzr
Copy link
Author

leogtzr commented May 8, 2020

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