Type.class
public enum Type {
TRIANGLE, CIRCLE, RECTANGLE
}
Shape.class
public abstract class Shape implements Cloneable {
protected Type type;
abstract void draw();
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
Rectangle.class
public class Rectangle extends Shape {
public Rectangle() {
this.type = Type.RECTANGLE;
}
@Override
void draw() {
System.out.println("[Rectangle]입니다.");
}
}
Triangle.class
public class Triangle extends Shape {
public Triangle() {
this.type = Type.TRIANGLE;
}
@Override
void draw() {
System.out.println("[Triangle]입니다.");
}
}
Circle.class
public class Circle extends Shape {
public Circle() {
this.type = Type.CIRCLE;
}
@Override
void draw() {
System.out.println("[Circle]입니다.");
}
}
ShapeStroe.class
public class ShapeStore {
private static Map<Type, Shape> shapeMap = new HashMap<Type, Shape>();
public void registerShape() {
Rectangle rec = new Rectangle();
Circle cir = new Circle();
Triangle tri = new Triangle();
shapeMap.put(rec.type, rec);
shapeMap.put(cir.type, cir);
shapeMap.put(tri.type, tri);
}
public Shape getShape(Type type) {
return (Shape) shapeMap.get(type).clone();
}
}
Main.class
public static void main(String[] args) {
ShapeStore manager = new ShapeStore();
manager.registerShape();
Circle cir1 = (Circle)manager.getShape(Type.CIRCLE);
cir1.draw();
Circle cir2 = (Circle)manager.getShape(Type.CIRCLE);
cir2.draw();
Rectangle rec1 = (Rectangle)manager.getShape(Type.RECTANGLE);
rec1.draw();
Triangle tri1 = (Triangle)manager.getShape(Type.TRIANGLE);
tri1.draw();
}
실행결과
>>>[Circle]입니다.
>>>[Circle]입니다.
>>>[Rectangle]입니다.
>>>[Triangle]입니다.
참조: